Skip to content

Commit

Permalink
6.4.1-rc4 (#1126)
Browse files Browse the repository at this point in the history
- Some more fixes
  • Loading branch information
tmolitor-stud-tu committed Jul 23, 2024
2 parents 4b88e08 + 105766e commit 3b7677a
Show file tree
Hide file tree
Showing 8 changed files with 424 additions and 30 deletions.
11 changes: 4 additions & 7 deletions Monal/Classes/ActiveChatsViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,8 @@ -(void) handleRefreshDisplayNotification:(NSNotification*) notification
{
// filter notifcations from within this class
if([notification.object isKindOfClass:[ActiveChatsViewController class]])
{
return;
}
[self refreshDisplay];
[self refresh];
}

-(void) handleContactRemoved:(NSNotification*) notification
Expand Down Expand Up @@ -410,8 +408,7 @@ -(void) sheetDismissed
-(void) refresh
{
dispatch_async(dispatch_get_main_queue(), ^{
if(self.unpinnedContacts.count == 0 && self.pinnedContacts.count == 0)
[self refreshDisplay]; // load contacts
[self refreshDisplay]; // load contacts
[self segueToIntroScreensIfNeeded];
});
}
Expand Down Expand Up @@ -523,7 +520,7 @@ -(void) syncContacts
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError* _Nullable error) {
if(granted)
{
NSString* countryCode = @"+49"; //[[HelperTools defaultsDB] objectForKey:@"Quicksy_countryCode"];
NSString* countryCode = [[HelperTools defaultsDB] objectForKey:@"Quicksy_countryCode"];
NSCharacterSet* allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"+0123456789"] invertedSet];
NSMutableDictionary* numbers = [NSMutableDictionary new];

Expand All @@ -540,7 +537,7 @@ -(void) syncContacts
if(countryCode != nil && ![number hasPrefix:@"+"] && ![number hasPrefix:@"00"])
{
DDLogVerbose(@"Adding country code '%@' to number: %@", countryCode, number);
number = [NSString stringWithFormat:@"%@%@", countryCode, number];
number = [NSString stringWithFormat:@"%@%@", countryCode, [number hasPrefix:@"0"] ? [number substringFromIndex:1] : number];
}
numbers[number] = name;
}
Expand Down
243 changes: 243 additions & 0 deletions Monal/Classes/CountryCodes.swift

Large diffs are not rendered by default.

25 changes: 9 additions & 16 deletions Monal/Classes/Quicksy_RegisterAccount.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,23 +50,9 @@ class Quicksy_State: ObservableObject {
var countryCode: String?
}

struct Quicksy_Country: Identifiable, Hashable {
let id = UUID()
let name: String
let code: String
let mobilePattern: String
}

struct Quicksy_RegisterAccount: View {
var delegate: SheetDismisserProtocol
let countries: [Quicksy_Country] = [
Quicksy_Country(name: NSLocalizedString("Germany", comment:"quicksy country"), code: "+49", mobilePattern: "^1\\d{10}$") ,
Quicksy_Country(name: NSLocalizedString("United States", comment:"quicksy country"), code: "+1", mobilePattern: "^\\d{10}$"),
Quicksy_Country(name: NSLocalizedString("Canada", comment:"quicksy country"), code: "+1", mobilePattern: "^\\d{10}$"),
Quicksy_Country(name: NSLocalizedString("United Kingdom", comment:"quicksy country"), code: "+44", mobilePattern: "^7\\d{9}$"),
Quicksy_Country(name: NSLocalizedString("Australia", comment:"quicksy country"), code: "+61", mobilePattern: "^4\\d{8}$"),
Quicksy_Country(name: NSLocalizedString("India", comment:"quicksy country"), code: "+91", mobilePattern: "^[789]\\d{9}$"),
]
let countries: [Quicksy_Country] = COUNTRY_CODES
@StateObject private var overlay = LoadingOverlayState()
@ObservedObject var state = Quicksy_State()
@State private var currentIndex = 0
Expand Down Expand Up @@ -141,7 +127,7 @@ struct Quicksy_RegisterAccount: View {
guard let selectedCountry = selectedCountry else {
return false
}
let phonePredicate = NSPredicate(format: "SELF MATCHES %@", selectedCountry.mobilePattern)
let phonePredicate = NSPredicate(format: "SELF MATCHES %@", selectedCountry.pattern)
return phoneNumber.allSatisfy { $0.isNumber } && phoneNumber.count > 0 && phonePredicate.evaluate(with: phoneNumber)
}

Expand Down Expand Up @@ -280,6 +266,13 @@ struct Quicksy_RegisterAccount: View {
})
.onAppear {
selectedCountry = countries[0]
print("######## \(String(describing:Locale.current.regionCode))")
print("######## \(String(describing:Locale(identifier: "en_US").localizedString(forRegionCode:Locale.current.regionCode ?? "en")))")
for country in countries {
if country.name == Locale.current.localizedString(forRegionCode:Locale.current.regionCode ?? "en") || country.name == Locale(identifier: "en_US").localizedString(forRegionCode:Locale.current.regionCode ?? "en") {
selectedCountry = country
}
}
//ios>=15
//phoneNumberFocused = true
}
Expand Down
19 changes: 12 additions & 7 deletions Monal/Classes/xmpp.m
Original file line number Diff line number Diff line change
Expand Up @@ -3241,14 +3241,19 @@ -(void) sendIq:(XMPPIQ*) iq withResponseHandler:(monal_iq_handler_t) resultHandl

-(void) sendIq:(XMPPIQ*) iq withHandler:(MLHandler*) handler
{
if(handler)
{
DDLogVerbose(@"Adding %@ to iqHandlers...", handler);
@synchronized(_iqHandlers) {
_iqHandlers[iq.id] = [@{@"iq":iq, @"timeout":@(IQ_TIMEOUT), @"handler":handler} mutableCopy];
//serialize this state update with other receive queue updates
//not doing this will make it race with a readState call in the receive queue before the write of this update can happen,
//which will remove this entry from state and the iq answer received later on be discarded
[self dispatchAsyncOnReceiveQueue:^{
if(handler)
{
DDLogVerbose(@"Adding %@ to iqHandlers...", handler);
@synchronized(self->_iqHandlers) {
self->_iqHandlers[iq.id] = [@{@"iq":iq, @"timeout":@(IQ_TIMEOUT), @"handler":handler} mutableCopy];
}
}
}
[self send:iq]; //this will also call persistState --> we don't need to do this here explicitly (to make sure our iq delegate is stored to db)
[self send:iq]; //this will also call persistState --> we don't need to do this here explicitly (to make sure our iq delegate is stored to db)
}];
}

-(void) send:(MLXMLNode*) stanza
Expand Down
4 changes: 4 additions & 0 deletions Monal/Monal.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@
845EFFBE2918723D00C1E03E /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = C1E4654624EE517000CA5AAF /* Localizable.strings */; };
846DF27C2937FAA600AAB9C0 /* ChatPlaceholder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 846DF27B2937FAA600AAB9C0 /* ChatPlaceholder.swift */; };
848227912C4A6194003CCA33 /* MLPlaceholderViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 848227902C4A6194003CCA33 /* MLPlaceholderViewController.m */; };
848501342C4F2B6D00C1B693 /* CountryCodes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 848501332C4F2B6D00C1B693 /* CountryCodes.swift */; };
848717F3295ED64600B8D288 /* MLCall.m in Sources */ = {isa = PBXBuildFile; fileRef = 848717F1295ED64500B8D288 /* MLCall.m */; };
848904A9289C82C30097E19C /* SCRAM.m in Sources */ = {isa = PBXBuildFile; fileRef = 848904A8289C82C30097E19C /* SCRAM.m */; };
848C73E02BDF2014007035C9 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 848C73DF2BDF2014007035C9 /* PrivacyInfo.xcprivacy */; };
Expand Down Expand Up @@ -586,6 +587,7 @@
845D636A2AD4AEDA0066EFFB /* ImageViewer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImageViewer.swift; sourceTree = "<group>"; };
846DF27B2937FAA600AAB9C0 /* ChatPlaceholder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatPlaceholder.swift; sourceTree = "<group>"; };
848227902C4A6194003CCA33 /* MLPlaceholderViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MLPlaceholderViewController.m; sourceTree = "<group>"; };
848501332C4F2B6D00C1B693 /* CountryCodes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CountryCodes.swift; sourceTree = "<group>"; };
848717F1295ED64500B8D288 /* MLCall.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = MLCall.m; path = Classes/MLCall.m; sourceTree = SOURCE_ROOT; };
848717F2295ED64500B8D288 /* MLCall.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MLCall.h; path = Classes/MLCall.h; sourceTree = SOURCE_ROOT; };
848904A8289C82C30097E19C /* SCRAM.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SCRAM.m; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1269,6 +1271,7 @@
84C1CD532A8F6196007076ED /* MLStreamRedirect.h */,
844921E92C29F9A000B99A9C /* MLDelayableTimer.m */,
844921EB2C29F9BE00B99A9C /* MLDelayableTimer.h */,
848501332C4F2B6D00C1B693 /* CountryCodes.swift */,
);
name = tools;
sourceTree = "<group>";
Expand Down Expand Up @@ -2188,6 +2191,7 @@
542CF3FF2763314F002C3710 /* hsluv.c in Sources */,
8420EA9D2915E5100038FF40 /* OmemoState.m in Sources */,
389E298C25E901CA009A5268 /* MLAudioRecoderManager.m in Sources */,
848501342C4F2B6D00C1B693 /* CountryCodes.swift in Sources */,
84C1CD522A8F617F007076ED /* MLStreamRedirect.m in Sources */,
26CC57C923A0892800ABB92A /* MLMessageProcessor.m in Sources */,
C18E757C245E8AE900AE8FB7 /* MLPipe.m in Sources */,
Expand Down
16 changes: 16 additions & 0 deletions scripts/exportOptions/Quicksy_Stable_iOS_ExportOptions.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>method</key>
<string>app-store</string>
<key>compileBitcode</key>
<false/>
<key>uploadBitcode</key>
<false/>
<key>signingStyle</key>
<string>automatic</string>
<key>teamID</key>
<string>S8D843U34Y</string>
</dict>
</plist>
135 changes: 135 additions & 0 deletions scripts/itu_pdf_to_swift.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
import requests
import io
from pypdf import PdfReader
import re
import logging

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)-7s] %(name)s {%(threadName)s} %(filename)s:%(lineno)d: %(message)s")
logger = logging.getLogger(__name__)

class Quicksy_Country:
def __init__(self, name, code, pattern):
self.name = name
self.code = code
self.pattern = pattern

def __repr__(self):
return f"Quicksy_Country(name: NSLocalizedString(\"{self.name}\", comment:\"quicksy country\"), code: \"{self.code}\", pattern: \"{self.pattern}\") ,"

def parse_pdf(pdf_data):
country_regex = re.compile(r'^(?P<country>[^0-9]+)[ ]{32}(?P<code>[0-9]+)[ ]{32}(?P<international_prefix>.+)[ ]{32}(?P<national_prefix>.+)[ ]{32}(?P<format>.+ digits)[ ]{32}(?P<end>.*)$')
country_end_regex = re.compile(r'^(?P<dst>.*)([ ]{32}(?P<notes>.+))?$')
countries = {}
pdf = PdfReader(io.BytesIO(pdf_data))
pagenum = 0
last_entry = None
for page in pdf.pages:
pagenum += 1
countries[pagenum] = []
logger.info(f"Starting to analyze page {pagenum}...")
text = page.extract_text(extraction_mode="layout", layout_mode_space_vertically=False)
if text and "Country/geographical area" in text and "Country" in text and "International" in text and "National" in text and "National (Significant)" in text and "UTC/DST" in text and "Note" in text:
for line in text.split("\n"):
#this is faster than having a "{128,} in the compiled country_regex
match = country_regex.match(re.sub("[ ]{128,}", " "*32, line))
if match == None:
# check if this is just a linebreak in the country name and append the value to the previous country
if re.sub("[ ]{128,}", " "*32, line) == line.strip() and last_entry != None and "Annex to ITU" not in line:
logger.debug(f"Adding to last country name: {line=}")
countries[pagenum][last_entry].name += f" {line.strip()}"
else:
last_entry = None # don't append line continuations of non-real countries to a real country
else:
match = match.groupdict() | {"dst": None, "notes": None}
if match["end"] and match["end"].strip() != "":
end_splitting = match["end"].split(" "*32)
if len(end_splitting) >= 1:
match["dst"] = end_splitting[0]
if len(end_splitting) >= 2:
match["notes"] = end_splitting[1]
match = {key: (value.strip() if value != None else None) for key, value in match.items()}
# logger.debug("****************")
# logger.debug(f"{match['country'] = }")
# logger.debug(f"{match['code'] = }")
# logger.debug(f"{match['international_prefix'] = }")
# logger.debug(f"{match['national_prefix'] = }")
# logger.debug(f"{match['format'] = }")
# logger.debug(f"{match['dst'] = }")
# logger.debug(f"{match['notes'] = }")

if match["dst"] == None: # all real countries have a dst entry
last_entry = None # don't append line continuations of non-real countries to a real country
else:
country_code = f"+{match['code']}"
pattern = subpattern_matchers(match['format'], True)
superpattern = matcher(pattern, r"(\([0-9/]+\))[ ]*\+[ ]*(.+)[ ]+digits", match['format'], lambda result: result)
if pattern == None and superpattern != None:
#logger.debug(f"Trying superpattern: '{match['format']}' --> '{superpattern.group(1)}' ## '{superpattern.group(2)}'")
subpattern = subpattern_matchers(superpattern.group(2), False)
if subpattern != None:
pattern = re.sub("/", "|", superpattern.group(1)) + subpattern
if pattern == None:
logger.warning(f"Unknown format description for {match['country']} ({country_code}): '{match['format']}'")
pattern = "[0-9]*"
country = Quicksy_Country(match['country'], country_code, f"^{pattern}$")
countries[pagenum].append(country)
last_entry = len(countries[pagenum]) - 1
logger.info(f"Page {pagenum}: Found {len(countries[pagenum])} countries so far...")

return [c for cs in countries.values() for c in cs]

def matcher(previous_result, regex, text, closure):
if previous_result != None:
return previous_result
matches = re.match(regex, text)
if matches == None:
return None
else:
return closure(matches)

def subpattern_matchers(text, should_end_with_unit):
if should_end_with_unit:
if text[-6:] != "digits":
logger.error(f"should_end_with_unit set but not ending in 'digits': {text[-6:] = }")
return None
text = text[:-6]

def subdef(result):
retval = f"[0-9]{{"
grp1 = result.group(1) if result.group(1) != "up" else "1"
retval += f"{grp1}"
if result.group(3) != None:
retval += f",{result.group(3)}"
retval += f"}}"
return retval
pattern = []
parts = [x.strip() for x in text.split(",")]
for part in parts:
result = matcher(None, r"(up|[0-9]+)([ ]*to[ ]*([0-9]+)[ ]*)?", part, subdef)
#logger.debug(f"{part=} --> {result=}")
if result != None:
pattern.append(result)
if len(pattern) == 0:
return None
return "(" + "|".join(pattern) + ")"

logger.info("Downloading PDF...")
response = requests.get("https://www.itu.int/dms_pub/itu-t/opb/sp/T-SP-E.164C-2011-PDF-E.pdf")
logger.info("Parsing PDF...")
countries = parse_pdf(response.content)
print("""// This file was automatically generated by scripts/itu_pdf_to_swift.py
// Please run this python script again to update this file
// Example ../scripts/itu_pdf_to_swift.py > Classes/CountryCodes.swift
public struct Quicksy_Country: Identifiable, Hashable {
public let id = UUID()
public let name: String
public let code: String
public let pattern: String
}
""")
print(f"public let COUNTRY_CODES: [Quicksy_Country] = [")
for country in countries:
print(f" {country}")
print(f"]")
1 change: 1 addition & 0 deletions scripts/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PyPDF @ git+https://github.com/py-pdf/pypdf@4.3.1

0 comments on commit 3b7677a

Please sign in to comment.