Commit Graph

147 Commits

Author SHA1 Message Date
Max Radermacher
98f3c03d41
Remove unused OWSDispatch class 2023-02-27 14:17:05 -08:00
Max Radermacher
7ac03076e6
Consolidate link preview fetching code 2023-02-21 12:49:25 -08:00
Evan Hahn
96cc668158
Move isWeakPin function, add tests
This change moves `PinSetupViewController`'s `isWeakPin` method to
`OWS2FAManager`, adds tests, and adds an additional length check.

This change should have no user impact and is useful for an upcoming
task.
2023-02-21 09:00:57 -08:00
Max Radermacher
56154557dd
Add isStructurallyValidE164
This merges & replaces `resemblesE164:` and `isValidE164`.

Co-authored-by: Evan Hahn <69474926+EvanHahn-Signal@users.noreply.github.com>
2023-02-13 13:45:00 -08:00
Harry
ff7567370c
Add request/response types for Registration Session APIs
* Add UnknownEnumCodable+tests

* Add Registration session requests and responses + tests

* Use shared Accept-Language code
2023-02-06 12:44:31 -08:00
Evan Hahn
3cacae049f
Add utilities for recovering corrupted FTS tables
This change should have no user impact. These utilities are currently
unused but will be soon.
2023-02-06 10:38:53 -06:00
Harry
6576349613
Migrate KeyBackupService to the Swift Way™️
* Put KeyBackupService in its own folder

* Put SDSKeyValueStore in its own directory

* Put SDSDatabaseStorage in its own directory

* Stop doing useless dispatches in SDSTransactable

* Add V2 DB classes

* Wrap SDSKeyValueStore in a protocol and factory

* Make TSConstantsProtocol public to take it as a param in other places

* Take explicit transactions and do single lookups in TSAccountManager registration state methods

* Take explicit transaction on OWS2FAManager

* Make KeyBackupService an instance that takes dependencies on init

* Protocolize KeyBackupService

* Put Dependencies+SSK in its own directory

* Add DependenciesBridge

* add ViewControllerContext

* used shared context in OnboardingController

* Don't check KeyBackupService in RemoteConfigManager; the one and only callsite already checks it separately

* All the random cleanup that needed to happen to get the app to build again.

* Add mock dbv2 classes

* Migrate existing KeyBackupServiceTests

* Namespace KBS shims

* DBV2 -> DB, after changing the min swiftlint type length to 2 chars

* add toy example

* Unwrap writes as reads

* pr comments

* pr comments 2: return of the nits

* final Pr comment
2023-02-02 09:42:05 -08:00
Evan Hahn
c1f1e9511c
Move checker to separate file 2023-01-25 17:57:16 -06:00
Evan Hahn
abd130a4c2
Clean up preauth challenge request
This change should have no user impact. It makes a few cleanups to
`OWSRequestFactory.requestPreauthChallengeRequest`:

- Adds tests
- Converts it to Swift
- Renames it to `requestPreauthChallenge`
- URL-encodes the parameters. This required some additional scaffolding;
  see `URLPathComponents`.
2023-01-25 14:22:22 -06:00
Max Radermacher
0db3f79f88
Check for problematic characters in link previews 2023-01-24 18:00:40 -08:00
Max Radermacher
62415025d4
Add & use Error.shortDescription in a few places 2023-01-23 10:22:54 -08:00
Evan Hahn
62215b97c3
Clean up "report spam" request code
This change should have no user impact.

This makes the following changes to `OWSRequestFactory.reportSpam`:

- Converts it to Swift
- Adds tests
- Handles a server GUID that couldn't be URL-encoded. For example, if it
  contained spaces, we'd crash constructing the URL. No longer!
- Handles an empty server GUID
2023-01-20 14:15:33 -06:00
Evan Hahn
ad71c9661d Remove unused orderOfMagnitudeOf method
`OWSAnalytics.orderOfMagnitudeOf` is no longer used as of
f973af5a83. This removes it and its
associated tests.
2022-12-06 14:27:59 -06:00
Evan Hahn
61fe312ad6 Add tests for CRC32 2022-12-06 11:55:46 -06:00
Max Radermacher
3a2b5a37bf Fix SwiftLint violations 2022-11-29 14:47:23 -08:00
Max Radermacher
0fb57a74ae
Fix various bugs in OWSHttpHeaders
First, `OWSHttpHeaders(httpHeaders:)` completely ignored its argument.
This doesn’t actually seem to have led to any bugs in practice; one time
the caller appears to have worked around the bug by adding the headers
again, and another time the caller relied on `allHTTPHeaderFields`
ignoring unrelated values.

Second, `URLRequest` has both `addValue` and `setValue` methods for its
headers. The former will construct a comma-separated list if the header
is already set, and the latter will replace it if it’s already set. (If
the header hasn’t been set, the two are equivalent, which is why call
sites weren’t broken even though they used the wrong method.) This was
broken only in multi-part uploads, but it was broken for "User-Agent"
and "Accept-Language", both of which are non-critical.

Third, `URLRequest`’s `allHTTPHeaderFields` doesn’t behave the way you
might expect. There’s a unit test which demonstrates some of the weird
behaviors, but any fields that aren’t present in the assigned value
aren’t touched. It seems as though most code was written as if calling
this method would fully replace *all* the HTTP headers. (The
`replace(…)` and `removeAllHeaders` methods have been removed because
they didn’t do what you’d think, and they weren’t necessary.)

Also:
* Remove Obj-C support from OWSHttpHeaders
* Move & simplify tests for HTTP Retry-After header
* Remove unused `asConnectionFailureError` method
2022-11-22 11:43:55 -08:00
Evan Hahn
5c55c848d1 Add card validation code
This code is currently dormant, but will be useful in an upcoming
change.

Check the tests to see how this works.
2022-11-11 14:24:41 -06:00
Evan Hahn
ec78cc3a0a
Hide Apple Pay UI when the server disallows your region
_I recommend reviewing this with whitespace changes disabled._

The server's `global.donations.apayDisabledRegions` is a list of regions
(phone number prefixes) where Apple Pay is disallowed. This respects
that.
2022-11-10 16:19:47 -06:00
Evan Hahn
74d8d25a04 Move SignalServiceKit string tests to correct file
_This change should have no user impact._

We add some stuff to `String` in `SignalServiceKit`.

Before, we tested this in the `SignalTests` target. Now, it's in the
`SignalServiceKitTests` target.

All I did was move some lines. I didn't change the tests at all.

I think this is a good change on its own but it may be useful in an
upcoming change.
2022-11-07 14:31:15 -08:00
Sasha Weiss
1cb90e245f
Fetch and persist remote megaphones 2022-10-26 15:03:08 -07:00
Evan Hahn
623b1909b2
Prefer Decimal over NSDecimalNumber
This change should have no user impact.

We use `NSDecimalNumber` and `Decimal`. This tries to standardize on
`Decimal` where possible (though the former is still needed in a few
places).

Mostly a mechanical change, though a few little things changed.
2022-10-18 09:43:46 -05:00
Evan Hahn
370ff654e7
Change license to AGPL
Change license to AGPL

This commit:

- Updates the `LICENSE` file

- Start every file with something like:

      // Copyright YEAR_FIRST_PUBLISHED Signal Messenger, LLC
      // SPDX-License-Identifier: AGPL-3.0-only

---

First, I removed existing license headers with this Ruby 3.1.2 script:

    require 'set'

    EXTENSIONS_TO_CHECK = Set['.h', '.hpp', '.cpp', '.m', '.mm', '.pch', '.swift']

    same = 0
    different = 0

    all_files = `git ls-files`.lines.map { |line| line.strip }
    all_files.each do |relative_path|
      if relative_path == 'Pods'
        next
      end

      unless EXTENSIONS_TO_CHECK.include? File.extname(relative_path)
        next
      end

      path = File.expand_path(relative_path)

      contents = File.read(path)
      new_contents = contents.sub(/\/\/\n\/\/  Copyright .*\n\/\/\n\n/, '')

      if contents == new_contents
        same += 1
      else
        different += 1
      end

      File.write(path, new_contents)
    end

    puts "updated #{different} file(s), left #{same} untouched"

I'm sure this script could be improved, but it worked well enough.

Then, I created `Scripts/lint/lint-license-headers` and ran it to auto-
fix a lot of files. This changed the mode of some files, but I think
that's actually desirable. For example,
`SignalServiceKit/src/Util/AppContext.m` previously had a mode of
`0755/-rwxr-xr-x`, and it's now `0644/-rw-r--r--`.

Then I fixed some stragglers and updated the precommit script.

See [a similar change in the Desktop app][0].

[0]: 8bfaf598af
2022-10-13 08:25:37 -05:00
Evan Hahn
349681ff85
Attempt to recover corrupted databases
If a user's database is corrupted, we now try to fix it. I recommend
reviewing `DatabaseRecovery` to see how this works, and
`DatabaseRecoveryViewController` for the bulk of the UI.
2022-10-06 16:42:19 -05:00
Evan Hahn
a066511a62 Remove useless test setup/teardown
We had a lot of functions like this, which are useless:

    override func setUp() {
        super.setUp()
    }

This removes them.
2022-10-04 14:06:34 -07:00
Evan Hahn
3cf796e55c
Add utility for remaining disk space 2022-09-22 09:28:42 -07:00
Max Radermacher
3fdaf367e1
Consolidate Int <-> Data logic 2022-09-21 12:08:45 -07:00
Max Radermacher
73c70d328f
Add UUID.from(data:) that returns the byte count
Co-authored-by: Evan Hahn <69474926+EvanHahn-Signal@users.noreply.github.com>
2022-09-21 11:34:41 -07:00
Evan Hahn
5a15f2f224
Move message padding to Data
Message padding is currently on `NSData`.

This moves it to Data, and rewrites everything in Swift.

Tested this by sending and receiving a message.
2022-09-15 12:50:20 -05:00
Evan Hahn
4445f0cedf
Improvements to PNG transcoding 2022-09-13 23:22:50 +00:00
Evan Hahn
42055d6f50 Actually test an APNG in detector code
This change should have no user impact.

`NSData#isAnimatedPngData` detects whether something is an animated
PNG. Its tests don't actually check a real APNG, though. This adds such
a test.
2022-09-12 20:27:53 +00:00
Evan Hahn
59dde0bc05 APNG tests don't need special Signal-specific behavior
This change should have no user impact.

These tests don't need to inherit from `SSKBaseTestSwift`. They can just
inherit from `XCTestCase`.
2022-09-12 18:59:19 +00:00
Nora Trapp
942ba23d87 Ignore unregistered errors from all non-contact threads 2022-09-08 09:04:07 -07:00
Max Radermacher
fec0b0417b
Use UUID.data instead of reimplementing its logic
Also add a few more tests for remote config buckets.
2022-09-06 12:41:25 -07:00
Harry
7ee39eef63
Add SystemStoryManager
* Add OnboardingStoryManager

* mark onboarding story viewed

* Add tests and fix issues that came up from testing

* up test timeout for slower CI

* rename SystemStoryManager and put into dependency injecton container

* Use viewed state on StoryMessage itself. Have SystemStoryManager observe app lifecyle events to automatically manage the onboarding story

* use iOS assets which are now in s3

* todo cleanup

* increment timestamp for uniqueness

* pr comments

* change literal delimiter

* Add ChainedPromise utility, tests, and use in SystemStoryManager

* discretionarily observe app backgrounding in SystemStoryManager

* renaming from PR comments
2022-08-30 14:49:59 -07:00
Evan Hahn
c988fdfee6 Convert OWSAnalyticsTests to Swift
This is a test-only change that shouldn't affect users.
2022-07-28 13:03:09 -05:00
Max Radermacher
ed63a2aeac
Remove trailing comma
This fixes our violation of [SwiftLint's `trailing_comma` rule][0].

[0]: https://realm.github.io/SwiftLint/trailing_comma.html
2022-07-08 08:39:47 -05:00
Max Radermacher
919e744333 Show "0:00", not "0", for audio message playback
If the formatter was fed a fractional number of seconds, it would try to
render it with `durationFormatterS` and would get back "0".
2022-05-06 11:43:04 -07:00
Evan Hahn
04d7bb7462 Stop using arc4random in Swift files
This removes calls to `arc4random` and `arc4random_uniform` and replaces
them with calls to `Int.random` or equivalent.

These are a little less readable, which may be [why SwiftLint doesn't
like them][0]. (SwiftLint calls them "legacy", possibly because they're
not strong random number generators, but I couldn't find a clear
explanation for this anywhere, including [the original PR][1].)

This is the kind of change that's error-prone, so I wrote [a simple
script to help avoid regressions][2]. The script runs 10,000 iterations
of the old and new RNG and compares the ranges, reporting differences.
(Some differences are likely, like the ones that involve floats; others
are very unlikely to have differences.)

`git grep arc4random | grep swift` returns no results after this change.
Same for [everything else SwiftLint checks for][3].

[0]: https://realm.github.io/SwiftLint/legacy_random.html
[1]: https://github.com/realm/SwiftLint/pull/2419
[2]: https://gist.github.com/EvanHahn-Signal/9c75c9f484f4778149cbde3eafc9b285
[3]: ea6cc50890/Source/SwiftLintFramework/Rules/Idiomatic/LegacyRandomRule.swift (L23-L27)
2022-05-03 10:19:07 -05:00
igor-signal
4a6473b448
Localize user-visible file sizes.
Use ByteCountFormatter with default settings to localize any download sizes that user might see.
2022-04-29 09:57:56 -05:00
Igor Solomennikov
f3b2118d0e [IOS-2364] Fix zero TimeInterval formatted as "0" instead of "0:00". 2022-04-28 10:55:11 -07:00
Max Radermacher
bc53916301 Convert all(Testable)?Flags to functions 2022-04-18 16:28:01 -07:00
Max Radermacher
05b0112c88 Rename buildFlagMap()allFlags
This matches the naming scheme used for `allFeatureFlags`.
2022-04-18 14:52:26 -07:00
Max Radermacher
91512d745c Don’t pass class or value lookup block
The class can be computed from `self`, and the lookup block is always
the same (essentially `self.value(forKey:)`), so there’s no need to
provide separate implementations for each subclass. The superclass can
provide a single implementation for all subclasses to share.
2022-04-18 14:52:26 -07:00
Max Radermacher
450b8035f3 Add unit tests for BaseFlags’ reflection APIs 2022-04-18 14:52:26 -07:00
Michelle Linington
41f78c5d12 Merge branch 'release/5.35.1' 2022-04-14 18:16:01 -07:00
Michelle Linington
e22bfcdc9b Add some version comparison tests 2022-04-14 16:44:16 -07:00
Igor Solomennikov
bd653bee3b Lint. 2022-04-12 17:38:21 -07:00
Igor Solomennikov
25810e0887 Add OWSFormatTest. 2022-04-12 17:38:21 -07:00
George Nachman
22c1cb8a22 Fetch phone numbers in a batch.
This is the first meaty part of optimizing
fetching display names.

Some contacts fall back to phone numbers as their
display names. This PR fetches them in a single
SQL query via
`OWSContactsManager.phoneNumbers(for:, transaction)`.

To achieve this, this PR introduces
`GRDBSignalAccountFinder.signalAccounts(for:,transaction:)`
to fetch many accounts at once.

In order to fetch many accounts at once, we need
to be able to fetch many values from a
ModelReadCache at once. So this PR introduces
`ModelReadCache.readValues(for:,transaction:)` and
`ModelReadCache.getValues(for:,transaction:,returnNilOnCacheMiss:)`.

Existing methods that operate on a single value
were refactored to use the batch methods.

This PR adds tests for this functionality, which
necessitated changing the visibility of various
private symbols and also improving the fake
profile manager to make it more configurable.

There's also a tiny optimization for Refinery to
avoid calling a closure that has no work to do.
This helps elide do-nothing SQL queries that would
otherwise have been introduced.
2022-03-17 12:46:33 -07:00
George Nachman
36119e4367 Introduce Refinery to help batch DB queries.
This PR is the first in a series that will
optimize looking up full names of group members.

The biggest source of slowness when opening a
group chat is looking up the full names of group
members in the search for duplicates. It is slow
because it requires multiple db queries for each
member.

The characterstic feature of this algorithm is the
iterative process of assigning names to signal
addresses. For example, some contacts' names may
be cached. For others, their profiles must be
fetched. For those without profiles, their phone
numbers must be formatted (which requires fetching
SignalAccounts). For those without phone numbers,
their user names must be formatted.

This PR creates a class called Refinery. Its job
is to make it easy to assign values to keys
through multiple passes, where each pass may
succeed only for a subset of keys.

This is useful because we will eventually issue a
single DB query for some of these passes.
2022-03-04 10:44:07 -08:00