Compare commits

..

17 Commits

Author SHA1 Message Date
c4c109e4a3 v0.2.12 (#30)
* added metadata to story tile.

* bumped version

* fixed metadata tile

* bumped version.

* fixed pinned stories not being refreshed.
2022-06-01 01:34:21 -07:00
b7720d0584 v0.2.12 (#29)
* added metadata to story tile.

* bumped version

* fixed metadata tile

* bumped version.
2022-06-01 01:13:21 -07:00
7d5788dec3 updated README.md 2022-05-28 00:03:46 -07:00
80a836c6b9 updated README.md 2022-05-28 00:02:03 -07:00
913be9fc5d v0.2.11 (#27)
* fixed pinned story tile.

* bumped version.
2022-05-27 16:18:36 -07:00
7fceebfd56 fixed poll. (#26) 2022-05-27 10:56:19 -07:00
b9909b6a44 v0.2.9 (#25)
* improved link preview.

* fixed offline mode.

* make refresh controller required.

* remove shouldRetry.

* fixed link preview.
2022-05-25 02:25:58 -07:00
9346542328 improved link preview. (#24) 2022-05-24 22:50:04 -07:00
e8c4e2b653 bumped version. 2022-05-23 11:56:57 -07:00
f6a92be68a fixed collapsed comments. 2022-05-23 11:56:30 -07:00
21c486b7cf fixed comment tile. 2022-05-23 11:52:51 -07:00
70b53ca771 bumped version. 2022-05-23 03:59:42 -07:00
d073604cc7 fixed poll cubit. 2022-05-23 03:58:23 -07:00
2ed74e70f1 fixed poll cubit. 2022-05-23 03:54:58 -07:00
d683a9e260 updated README.md 2022-05-23 03:37:27 -07:00
adbeaad69e updated fastlane. 2022-05-23 01:34:02 -07:00
7a14815c20 v0.2.8 (#23)
* added share extension.

* added action extension.

* added f-droid badge.

* bumped version.

* fixed android share extension.

* updated README.md

* updated README.md

* updated README.md
2022-05-23 01:30:22 -07:00
101 changed files with 1997 additions and 539 deletions

View File

@ -1,9 +1,9 @@
# <img width="64" src="https://user-images.githubusercontent.com/7277662/167775086-0b234f28-dee4-44f6-aae4-14a28ed4bbb6.png"> Hacki for Hacker News
A simple noiseless [Hacker News](https://news.ycombinator.com/) reader made with Flutter that is just enough.
A simple noiseless [Hacker News](https://news.ycombinator.com/) client made with Flutter that is just enough.
[![App Store](https://img.shields.io/itunes/v/1602043763?label=App%20Store)](https://apps.apple.com/us/app/hacki/id1602043763)
[![App Store](https://img.shields.io/itunes/v/1602043763?label=App%20Store)](https://apps.apple.com/us/app/hacki/id1602043763?platform=iphone)
[![Play Store](https://img.shields.io/badge/Play%20Store--yellow)](https://play.google.com/store/apps/details?id=com.jiaqifeng.hacki&hl=en_US&gl=US)
[![Visits Badge](https://badges.pufler.dev/visits/livinglist/Hacki)](https://badges.pufler.dev)
[![GitHub](https://img.shields.io/github/stars/livinglist/Hacki?style=social)](https://img.shields.io/github/stars/livinglist/Hacki?style=social)
@ -11,24 +11,27 @@ A simple noiseless [Hacker News](https://news.ycombinator.com/) reader made with
<noscript><a href="https://liberapay.com/jfeng_for_open_source/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a></noscript>
[<img src="assets/images/app_store_badge.png" height="50">](https://apps.apple.com/us/app/hacki/id1602043763) [<img src="assets/images/google_play_badge.png" height="50">](https://play.google.com/store/apps/details?id=com.jiaqifeng.hacki&hl=en_US&gl=US)
[<img src="assets/images/app_store_badge.png" height="50">](https://apps.apple.com/us/app/hacki/id1602043763?platform=iphone) [<img src="assets/images/google_play_badge.png" height="50">](https://play.google.com/store/apps/details?id=com.jiaqifeng.hacki&hl=en_US&gl=US) [<img src="assets/images/f_droid_badge.png" height="50">](https://f-droid.org/en/packages/com.jiaqifeng.hacki/)
Features:
- Log in using your Hacker News account.
- Browse stories from various categories.
- Submit links.
- Leave comments on stories.
- View and participate in polls.
- Search for stories.
- Submit stories.
- Pin stories.
- Mark stories as favorite.
- Browse comments and stories you have posted in the past.
- Search for stories on Hacker News.
- Leave comments.
- Collapse comments.
- View parent comments without scrolling up.
- View and participate in polls.
- Browse comments and stories you have posted.
- Vote on comments or stories.
- Pin stories to the top of home page.
- Get in-app notification when there is new reply to your stories or comments.
- Download stories for offline reading.
- Download stories and comments for offline reading.
- Pick up where you left off.
- Synced favorites and pins across devices. (iOS only)
- Launch from system share sheet.
- And more...

View File

@ -42,6 +42,12 @@
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -0,0 +1,4 @@
- You can now participate in polls.
- Pick up where you left off.
- Swipe left on comment tile to view its parents without scrolling all the way up.
- Huge performance boost.

View File

@ -1,16 +1,18 @@
Features:
- Log in using your Hacker News account.
- Browse stories from various categories.
- Submit links.
- Leave comments on stories.
- View and participate in polls.
- Search for stories.
- Submit stories.
- Pin stories.
- Mark stories as favorite.
- Browse comments and stories you have posted in the past.
- Search for stories on Hacker News.
- Leave comments.
- Collapse comments.
- View parent comments without scrolling up.
- View and participate in polls.
- Browse comments and stories you have posted.
- Vote on comments or stories.
- Pin stories to the top of home page.
- Get in-app notification when there is new reply to your stories or comments.
- Download stories for offline reading.
- Download stories and comments for offline reading.
- Pick up where you left off.
- Launch from system share sheet.
- And more...

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 712 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 672 KiB

View File

Before

Width:  |  Height:  |  Size: 931 KiB

After

Width:  |  Height:  |  Size: 931 KiB

View File

Before

Width:  |  Height:  |  Size: 298 KiB

After

Width:  |  Height:  |  Size: 298 KiB

View File

Before

Width:  |  Height:  |  Size: 247 KiB

After

Width:  |  Height:  |  Size: 247 KiB

View File

Before

Width:  |  Height:  |  Size: 496 KiB

After

Width:  |  Height:  |  Size: 496 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 393 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 696 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 903 KiB

View File

@ -1 +1 @@
Hacki is a simple noiseless Hacker News reader that is just enough.
Hacki is a simple noiseless Hacker News client that is just enough.

View File

@ -0,0 +1,10 @@
<?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>com.apple.security.application-groups</key>
<array>
<string>group.com.jiaqi.hacki</string>
</array>
</dict>
</plist>

View File

@ -0,0 +1,89 @@
//
// ActionViewController.swift
// Action Extension
//
// Created by Jiaqi Feng on 5/22/22.
//
import UIKit
import MobileCoreServices
import UniformTypeIdentifiers
class ActionViewController: UIViewController {
let hostAppBundleIdentifier = "com.jiaqi.hacki"
let sharedKey = "ShareKey"
var sharedText: [String] = []
let urlContentType = kUTTypeURL as String
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let content = extensionContext!.inputItems[0] as? NSExtensionItem {
if let contents = content.attachments {
for (index, attachment) in (contents).enumerated() {
handleUrl(content: content, attachment: attachment, index: index)
}
}
}
}
private func handleUrl (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
attachment.loadItem(forTypeIdentifier: urlContentType, options: nil) { [weak self] data, error in
if error == nil, let item = data as? URL, let this = self {
this.sharedText.append(item.absoluteString)
// If this is the last item, save imagesData in userDefaults and redirect to host app
if index == (content.attachments?.count)! - 1 {
let userDefaults = UserDefaults(suiteName: "group.\(this.hostAppBundleIdentifier)")
userDefaults?.set(this.sharedText, forKey: this.sharedKey)
userDefaults?.synchronize()
print(this.sharedText)
this.redirectToHostApp()
}
} else {
self?.dismissWithError()
}
}
}
private func dismissWithError() {
print("[ERROR] Error loading data!")
let alert = UIAlertController(title: "Error", message: "Error loading data", preferredStyle: .alert)
let action = UIAlertAction(title: "Error", style: .cancel) { _ in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
private func redirectToHostApp() {
let url = URL(string: "ShareMedia://dataUrl=\(sharedKey)#text")
var responder = self as UIResponder?
let selectorOpenURL = sel_registerName("openURL:")
while (responder != nil) {
if let application = responder as? UIApplication {
application.performSelector(inBackground: selectorOpenURL, with: url)
}
responder = responder!.next
}
extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
@IBAction func done() {
// Return any edited content to the host app.
// This template doesn't do anything, so we just echo the passed in items.
self.extensionContext!.completeRequest(returningItems: self.extensionContext!.inputItems, completionHandler: nil)
}
}

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="ObA-dk-sSI">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Image-->
<scene sceneID="7MM-of-jgj">
<objects>
<viewController title="Image" id="ObA-dk-sSI" customClass="ActionViewController" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="zMn-AG-sqS">
<rect key="frame" x="0.0" y="0.0" width="320" height="528"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<navigationBar contentMode="scaleToFill" horizontalCompressionResistancePriority="751" verticalCompressionResistancePriority="751" translatesAutoresizingMaskIntoConstraints="NO" id="NOA-Dm-cuz">
<items>
<navigationItem id="3HJ-uW-3hn">
<barButtonItem key="leftBarButtonItem" title="Done" style="done" id="WYi-yp-eM6">
<connections>
<action selector="done" destination="ObA-dk-sSI" id="Qdu-qn-U6V"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
<imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="9ga-4F-77Z"/>
</subviews>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="VVe-Uw-JpX" firstAttribute="trailing" secondItem="NOA-Dm-cuz" secondAttribute="trailing" id="A05-Pj-hrr"/>
<constraint firstItem="9ga-4F-77Z" firstAttribute="top" secondItem="NOA-Dm-cuz" secondAttribute="bottom" id="Fps-3D-QQW"/>
<constraint firstItem="NOA-Dm-cuz" firstAttribute="leading" secondItem="VVe-Uw-JpX" secondAttribute="leading" id="HxO-8t-aoh"/>
<constraint firstItem="VVe-Uw-JpX" firstAttribute="trailing" secondItem="9ga-4F-77Z" secondAttribute="trailing" id="Ozw-Hg-0yh"/>
<constraint firstItem="9ga-4F-77Z" firstAttribute="leading" secondItem="VVe-Uw-JpX" secondAttribute="leading" id="XH5-ld-ONA"/>
<constraint firstItem="VVe-Uw-JpX" firstAttribute="bottom" secondItem="9ga-4F-77Z" secondAttribute="bottom" id="eQg-nn-Zy4"/>
<constraint firstItem="NOA-Dm-cuz" firstAttribute="top" secondItem="VVe-Uw-JpX" secondAttribute="top" id="we0-1t-bgp"/>
</constraints>
<viewLayoutGuide key="safeArea" id="VVe-Uw-JpX"/>
</view>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<size key="freeformSize" width="320" height="528"/>
<connections>
<outlet property="imageView" destination="9ga-4F-77Z" id="5y6-5w-9QO"/>
<outlet property="view" destination="zMn-AG-sqS" id="Qma-de-2ek"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="X47-rx-isc" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>

View File

@ -0,0 +1,33 @@
<?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>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>NSExtensionActivationRule</key>
<dict>
<key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
<integer>1</integer>
<key>NSExtensionActivationSupportsWebPageWithMaxCount</key>
<integer>1</integer>
</dict>
<key>NSExtensionServiceAllowsFinderPreviewItem</key>
<true/>
<key>NSExtensionServiceAllowsTouchBarItem</key>
<true/>
<key>NSExtensionServiceFinderPreviewIconName</key>
<string>NSActionTemplate</string>
<key>NSExtensionServiceTouchBarBezelColorName</key>
<string>TouchBarBezel</string>
<key>NSExtensionServiceTouchBarIconName</key>
<string>NSActionTemplate</string>
</dict>
<key>NSExtensionMainStoryboard</key>
<string>MainInterface</string>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.ui-services</string>
</dict>
</dict>
</plist>

View File

@ -0,0 +1,176 @@
{
"info" : {
"version" : 1,
"author" : "Bakery"
},
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x",
"filename" : "notification40.png"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x",
"filename" : "notification60.png"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x",
"filename" : "settings58.png"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x",
"filename" : "settings87.png"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x",
"filename" : "spotlight80.png"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x",
"filename" : "spotlight120.png"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x",
"filename" : "iphone120.png"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x",
"filename" : "iphone180.png"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x",
"filename" : "ipadNotification20.png"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x",
"filename" : "ipadNotification40.png"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x",
"filename" : "ipadSettings29.png"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x",
"filename" : "ipadSettings58.png"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x",
"filename" : "ipadSpotlight40.png"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x",
"filename" : "ipadSpotlight80.png"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x",
"filename" : "ipad76.png"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x",
"filename" : "ipad152.png"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x",
"filename" : "ipadPro167.png"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x",
"filename" : "appstore1024.png"
},
{
"idiom" : "mac",
"size" : "16x16",
"scale" : "1x",
"filename" : "mac16.png"
},
{
"idiom" : "mac",
"size" : "16x16",
"scale" : "2x",
"filename" : "mac32.png"
},
{
"idiom" : "mac",
"size" : "32x32",
"scale" : "1x",
"filename" : "mac32.png"
},
{
"idiom" : "mac",
"size" : "32x32",
"scale" : "2x",
"filename" : "mac64.png"
},
{
"idiom" : "mac",
"size" : "128x128",
"scale" : "1x",
"filename" : "mac128.png"
},
{
"idiom" : "mac",
"size" : "128x128",
"scale" : "2x",
"filename" : "mac256.png"
},
{
"idiom" : "mac",
"size" : "256x256",
"scale" : "1x",
"filename" : "mac256.png"
},
{
"idiom" : "mac",
"size" : "256x256",
"scale" : "2x",
"filename" : "mac512.png"
},
{
"idiom" : "mac",
"size" : "512x512",
"scale" : "1x",
"filename" : "mac512.png"
},
{
"idiom" : "mac",
"size" : "512x512",
"scale" : "2x",
"filename" : "mac1024.png"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 566 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 744 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 502 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 835 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@ -0,0 +1,14 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
},
"colors" : [
{
"idiom" : "mac",
"color" : {
"reference" : "systemPurpleColor"
}
}
]
}

View File

@ -21,6 +21,8 @@ PODS:
- path_provider_ios (0.0.1):
- Flutter
- ReachabilitySwift (5.0.0)
- receive_sharing_intent (0.0.1):
- Flutter
- shared_preferences_ios (0.0.1):
- Flutter
- sqflite (0.0.2):
@ -46,6 +48,7 @@ DEPENDENCIES:
- flutter_local_notifications (from `.symlinks/plugins/flutter_local_notifications/ios`)
- flutter_secure_storage (from `.symlinks/plugins/flutter_secure_storage/ios`)
- path_provider_ios (from `.symlinks/plugins/path_provider_ios/ios`)
- receive_sharing_intent (from `.symlinks/plugins/receive_sharing_intent/ios`)
- shared_preferences_ios (from `.symlinks/plugins/shared_preferences_ios/ios`)
- sqflite (from `.symlinks/plugins/sqflite/ios`)
- synced_shared_preferences (from `.symlinks/plugins/synced_shared_preferences/ios`)
@ -74,6 +77,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/flutter_secure_storage/ios"
path_provider_ios:
:path: ".symlinks/plugins/path_provider_ios/ios"
receive_sharing_intent:
:path: ".symlinks/plugins/receive_sharing_intent/ios"
shared_preferences_ios:
:path: ".symlinks/plugins/shared_preferences_ios/ios"
sqflite:
@ -101,6 +106,7 @@ SPEC CHECKSUMS:
OrderedSet: aaeb196f7fef5a9edf55d89760da9176ad40b93c
path_provider_ios: 14f3d2fd28c4fdb42f44e0f751d12861c43cee02
ReachabilitySwift: 985039c6f7b23a1da463388634119492ff86c825
receive_sharing_intent: c0d87310754e74c0f9542947e7cbdf3a0335a3b1
shared_preferences_ios: 548a61f8053b9b8a49ac19c1ffbc8b92c50d68ad
sqflite: 6d358c025f5b867b29ed92fc697fd34924e11904
synced_shared_preferences: f722742b06d65c7315b8e9f56b794c9fbd5597f7

View File

@ -13,11 +13,36 @@
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
E51D52B0283B464E00FC8DD8 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E51D52AF283B464E00FC8DD8 /* ShareViewController.swift */; };
E51D52B3283B464E00FC8DD8 /* MainInterface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E51D52B1283B464E00FC8DD8 /* MainInterface.storyboard */; };
E51D52B7283B464E00FC8DD8 /* Share Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = E51D52AD283B464E00FC8DD8 /* Share Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
E530B1A8283B54DA004E8EB6 /* UniformTypeIdentifiers.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E530B1A7283B54DA004E8EB6 /* UniformTypeIdentifiers.framework */; };
E530B1AB283B54DA004E8EB6 /* Media.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E530B1AA283B54DA004E8EB6 /* Media.xcassets */; };
E530B1AD283B54DA004E8EB6 /* ActionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E530B1AC283B54DA004E8EB6 /* ActionViewController.swift */; };
E530B1B0283B54DA004E8EB6 /* MainInterface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E530B1AE283B54DA004E8EB6 /* MainInterface.storyboard */; };
E530B1B4283B54DA004E8EB6 /* Action Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = E530B1A6283B54DA004E8EB6 /* Action Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
E54B4753282B3B8900579261 /* HackiCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = E54B4752282B3B8900579261 /* HackiCore.swift */; };
E575B6F127EBC6DB002B1508 /* CloudKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E575B6F027EBC6DA002B1508 /* CloudKit.framework */; };
FC507E94AA7767C155787DB3 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BFB5AA41D6C22D228077D166 /* Pods_Runner.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
E51D52B5283B464E00FC8DD8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 97C146E61CF9000F007C117D /* Project object */;
proxyType = 1;
remoteGlobalIDString = E51D52AC283B464E00FC8DD8;
remoteInfo = "Share Extension";
};
E530B1B2283B54DA004E8EB6 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 97C146E61CF9000F007C117D /* Project object */;
proxyType = 1;
remoteGlobalIDString = E530B1A5283B54DA004E8EB6;
remoteInfo = "Action Extension";
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
9705A1C41CF9048500538489 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
@ -29,6 +54,18 @@
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
E51D52B8283B464E00FC8DD8 /* Embed App Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
E51D52B7283B464E00FC8DD8 /* Share Extension.appex in Embed App Extensions */,
E530B1B4283B54DA004E8EB6 /* Action Extension.appex in Embed App Extensions */,
);
name = "Embed App Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
@ -49,9 +86,21 @@
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
BFB5AA41D6C22D228077D166 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
DF5D5FFF325B7D5DFEE88A3F /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
E51D52AD283B464E00FC8DD8 /* Share Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "Share Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
E51D52AF283B464E00FC8DD8 /* ShareViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = "<group>"; };
E51D52B2283B464E00FC8DD8 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/MainInterface.storyboard; sourceTree = "<group>"; };
E51D52B4283B464E00FC8DD8 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
E530B1A6283B54DA004E8EB6 /* Action Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "Action Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
E530B1A7283B54DA004E8EB6 /* UniformTypeIdentifiers.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UniformTypeIdentifiers.framework; path = System/Library/Frameworks/UniformTypeIdentifiers.framework; sourceTree = SDKROOT; };
E530B1AA283B54DA004E8EB6 /* Media.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Media.xcassets; sourceTree = "<group>"; };
E530B1AC283B54DA004E8EB6 /* ActionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActionViewController.swift; sourceTree = "<group>"; };
E530B1AF283B54DA004E8EB6 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/MainInterface.storyboard; sourceTree = "<group>"; };
E530B1B1283B54DA004E8EB6 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
E530B1B9283B54E4004E8EB6 /* Action Extension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "Action Extension.entitlements"; sourceTree = "<group>"; };
E54B4752282B3B8900579261 /* HackiCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HackiCore.swift; sourceTree = "<group>"; };
E575B6EF27EBC6C6002B1508 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; };
E575B6F027EBC6DA002B1508 /* CloudKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CloudKit.framework; path = System/Library/Frameworks/CloudKit.framework; sourceTree = SDKROOT; };
E59F28EE283B477D00512089 /* Share Extension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "Share Extension.entitlements"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@ -64,6 +113,21 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
E51D52AA283B464E00FC8DD8 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
E530B1A3283B54DA004E8EB6 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
E530B1A8283B54DA004E8EB6 /* UniformTypeIdentifiers.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@ -83,6 +147,8 @@
children = (
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
E51D52AE283B464E00FC8DD8 /* Share Extension */,
E530B1A9283B54DA004E8EB6 /* Action Extension */,
97C146EF1CF9000F007C117D /* Products */,
D79CD63C88FF49EF451AFDDF /* Pods */,
B3F4F49CF582C662A01499C0 /* Frameworks */,
@ -93,6 +159,8 @@
isa = PBXGroup;
children = (
97C146EE1CF9000F007C117D /* Runner.app */,
E51D52AD283B464E00FC8DD8 /* Share Extension.appex */,
E530B1A6283B54DA004E8EB6 /* Action Extension.appex */,
);
name = Products;
sourceTree = "<group>";
@ -119,6 +187,7 @@
children = (
E575B6F027EBC6DA002B1508 /* CloudKit.framework */,
BFB5AA41D6C22D228077D166 /* Pods_Runner.framework */,
E530B1A7283B54DA004E8EB6 /* UniformTypeIdentifiers.framework */,
);
name = Frameworks;
sourceTree = "<group>";
@ -133,6 +202,29 @@
path = Pods;
sourceTree = "<group>";
};
E51D52AE283B464E00FC8DD8 /* Share Extension */ = {
isa = PBXGroup;
children = (
E59F28EE283B477D00512089 /* Share Extension.entitlements */,
E51D52AF283B464E00FC8DD8 /* ShareViewController.swift */,
E51D52B1283B464E00FC8DD8 /* MainInterface.storyboard */,
E51D52B4283B464E00FC8DD8 /* Info.plist */,
);
path = "Share Extension";
sourceTree = "<group>";
};
E530B1A9283B54DA004E8EB6 /* Action Extension */ = {
isa = PBXGroup;
children = (
E530B1B9283B54E4004E8EB6 /* Action Extension.entitlements */,
E530B1AA283B54DA004E8EB6 /* Media.xcassets */,
E530B1AC283B54DA004E8EB6 /* ActionViewController.swift */,
E530B1AE283B54DA004E8EB6 /* MainInterface.storyboard */,
E530B1B1283B54DA004E8EB6 /* Info.plist */,
);
path = "Action Extension";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@ -148,22 +240,60 @@
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
7714A105B2069B720D0DF18E /* [CP] Embed Pods Frameworks */,
E51D52B8283B464E00FC8DD8 /* Embed App Extensions */,
);
buildRules = (
);
dependencies = (
E51D52B6283B464E00FC8DD8 /* PBXTargetDependency */,
E530B1B3283B54DA004E8EB6 /* PBXTargetDependency */,
);
name = Runner;
productName = Runner;
productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
productType = "com.apple.product-type.application";
};
E51D52AC283B464E00FC8DD8 /* Share Extension */ = {
isa = PBXNativeTarget;
buildConfigurationList = E51D52BC283B464E00FC8DD8 /* Build configuration list for PBXNativeTarget "Share Extension" */;
buildPhases = (
E51D52A9283B464E00FC8DD8 /* Sources */,
E51D52AA283B464E00FC8DD8 /* Frameworks */,
E51D52AB283B464E00FC8DD8 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = "Share Extension";
productName = "Share Extension";
productReference = E51D52AD283B464E00FC8DD8 /* Share Extension.appex */;
productType = "com.apple.product-type.app-extension";
};
E530B1A5283B54DA004E8EB6 /* Action Extension */ = {
isa = PBXNativeTarget;
buildConfigurationList = E530B1B8283B54DA004E8EB6 /* Build configuration list for PBXNativeTarget "Action Extension" */;
buildPhases = (
E530B1A2283B54DA004E8EB6 /* Sources */,
E530B1A3283B54DA004E8EB6 /* Frameworks */,
E530B1A4283B54DA004E8EB6 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = "Action Extension";
productName = "Action Extension";
productReference = E530B1A6283B54DA004E8EB6 /* Action Extension.appex */;
productType = "com.apple.product-type.app-extension";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
97C146E61CF9000F007C117D /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1330;
LastUpgradeCheck = 1300;
ORGANIZATIONNAME = "";
TargetAttributes = {
@ -171,6 +301,12 @@
CreatedOnToolsVersion = 7.3.1;
LastSwiftMigration = 1100;
};
E51D52AC283B464E00FC8DD8 = {
CreatedOnToolsVersion = 13.3;
};
E530B1A5283B54DA004E8EB6 = {
CreatedOnToolsVersion = 13.3;
};
};
};
buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
@ -187,6 +323,8 @@
projectRoot = "";
targets = (
97C146ED1CF9000F007C117D /* Runner */,
E51D52AC283B464E00FC8DD8 /* Share Extension */,
E530B1A5283B54DA004E8EB6 /* Action Extension */,
);
};
/* End PBXProject section */
@ -203,6 +341,23 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
E51D52AB283B464E00FC8DD8 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E51D52B3283B464E00FC8DD8 /* MainInterface.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
E530B1A4283B54DA004E8EB6 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E530B1AB283B54DA004E8EB6 /* Media.xcassets in Resources */,
E530B1B0283B54DA004E8EB6 /* MainInterface.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
@ -286,8 +441,37 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
E51D52A9283B464E00FC8DD8 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E51D52B0283B464E00FC8DD8 /* ShareViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
E530B1A2283B54DA004E8EB6 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E530B1AD283B54DA004E8EB6 /* ActionViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
E51D52B6283B464E00FC8DD8 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = E51D52AC283B464E00FC8DD8 /* Share Extension */;
targetProxy = E51D52B5283B464E00FC8DD8 /* PBXContainerItemProxy */;
};
E530B1B3283B54DA004E8EB6 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = E530B1A5283B54DA004E8EB6 /* Action Extension */;
targetProxy = E530B1B2283B54DA004E8EB6 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
97C146FA1CF9000F007C117D /* Main.storyboard */ = {
isa = PBXVariantGroup;
@ -305,6 +489,22 @@
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
E51D52B1283B464E00FC8DD8 /* MainInterface.storyboard */ = {
isa = PBXVariantGroup;
children = (
E51D52B2283B464E00FC8DD8 /* Base */,
);
name = MainInterface.storyboard;
sourceTree = "<group>";
};
E530B1AE283B54DA004E8EB6 /* MainInterface.storyboard */ = {
isa = PBXVariantGroup;
children = (
E530B1AF283B54DA004E8EB6 /* Base */,
);
name = MainInterface.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
@ -362,12 +562,13 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 6;
CURRENT_PROJECT_VERSION = 3;
DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@ -376,7 +577,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.2.7;
MARKETING_VERSION = 0.2.12;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@ -498,12 +699,13 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 6;
CURRENT_PROJECT_VERSION = 3;
DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@ -512,7 +714,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.2.7;
MARKETING_VERSION = 0.2.12;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@ -528,12 +730,13 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 6;
CURRENT_PROJECT_VERSION = 3;
DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@ -542,7 +745,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.2.7;
MARKETING_VERSION = 0.2.12;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@ -553,6 +756,234 @@
};
name = Release;
};
E51D52B9283B464E00FC8DD8 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = "Share Extension/Share Extension.entitlements";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
GCC_C_LANGUAGE_STANDARD = gnu11;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Share Extension/Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = "Share Extension";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 15.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.jiaqi.hacki.Share-Extension";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
E51D52BA283B464E00FC8DD8 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = "Share Extension/Share Extension.entitlements";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
GCC_C_LANGUAGE_STANDARD = gnu11;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Share Extension/Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = "Share Extension";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 15.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.jiaqi.hacki.Share-Extension";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
E51D52BB283B464E00FC8DD8 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = "Share Extension/Share Extension.entitlements";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
GCC_C_LANGUAGE_STANDARD = gnu11;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Share Extension/Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = "Share Extension";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 15.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.jiaqi.hacki.Share-Extension";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Profile;
};
E530B1B5283B54DA004E8EB6 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIconExtension;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = "";
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = "Action Extension/Action Extension.entitlements";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
GCC_C_LANGUAGE_STANDARD = gnu11;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Action Extension/Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = "Open in Hacki";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 15.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.jiaqi.hacki.Action-Extension";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
E530B1B6283B54DA004E8EB6 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIconExtension;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = "";
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = "Action Extension/Action Extension.entitlements";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
GCC_C_LANGUAGE_STANDARD = gnu11;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Action Extension/Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = "Open in Hacki";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 15.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.jiaqi.hacki.Action-Extension";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
E530B1B7283B54DA004E8EB6 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIconExtension;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = "";
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CODE_SIGN_ENTITLEMENTS = "Action Extension/Action Extension.entitlements";
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
GCC_C_LANGUAGE_STANDARD = gnu11;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "Action Extension/Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = "Open in Hacki";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
IPHONEOS_DEPLOYMENT_TARGET = 15.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.0;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.jiaqi.hacki.Action-Extension";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Profile;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@ -576,6 +1007,26 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E51D52BC283B464E00FC8DD8 /* Build configuration list for PBXNativeTarget "Share Extension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E51D52B9283B464E00FC8DD8 /* Debug */,
E51D52BA283B464E00FC8DD8 /* Release */,
E51D52BB283B464E00FC8DD8 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E530B1B8283B54DA004E8EB6 /* Build configuration list for PBXNativeTarget "Action Extension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E530B1B5283B54DA004E8EB6 /* Debug */,
E530B1B6283B54DA004E8EB6 /* Release */,
E530B1B7283B54DA004E8EB6 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;

View File

@ -26,6 +26,17 @@
<string>$(MARKETING_VERSION)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>ShareMedia</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
@ -51,5 +62,9 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:example.com</string>
</array>
</dict>
</plist>

View File

@ -18,5 +18,9 @@
</array>
<key>com.apple.developer.ubiquity-kvstore-identifier</key>
<string>$(TeamIdentifierPrefix)$(CFBundleIdentifier)</string>
<key>com.apple.security.application-groups</key>
<array>
<string>group.com.jiaqi.hacki</string>
</array>
</dict>
</plist>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="j1y-V4-xli">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Share View Controller-->
<scene sceneID="ceB-am-kn3">
<objects>
<viewController id="j1y-V4-xli" customClass="ShareViewController" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" opaque="NO" contentMode="scaleToFill" id="wbc-yd-nQP">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="0.0" green="0.0" blue="0.0" alpha="0.0" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="1Xd-am-t49"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="CEy-Cv-SGf" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>

View File

@ -0,0 +1,21 @@
<?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>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>NSExtensionActivationRule</key>
<dict>
<key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
<integer>1</integer>
</dict>
</dict>
<key>NSExtensionMainStoryboard</key>
<string>MainInterface</string>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.share-services</string>
</dict>
</dict>
</plist>

View File

@ -0,0 +1,10 @@
<?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>com.apple.security.application-groups</key>
<array>
<string>group.com.jiaqi.hacki</string>
</array>
</dict>
</plist>

View File

@ -0,0 +1,334 @@
import UIKit
import Social
import MobileCoreServices
import Photos
class ShareViewController: SLComposeServiceViewController {
let hostAppBundleIdentifier = "com.jiaqi.hacki"
let sharedKey = "ShareKey"
var sharedMedia: [SharedMediaFile] = []
var sharedText: [String] = []
let imageContentType = kUTTypeImage as String
let videoContentType = kUTTypeMovie as String
let textContentType = kUTTypeText as String
let urlContentType = kUTTypeURL as String
let fileURLType = kUTTypeFileURL as String;
override func isContentValid() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad();
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
if let content = extensionContext!.inputItems[0] as? NSExtensionItem {
if let contents = content.attachments {
for (index, attachment) in (contents).enumerated() {
if attachment.hasItemConformingToTypeIdentifier(imageContentType) {
handleImages(content: content, attachment: attachment, index: index)
} else if attachment.hasItemConformingToTypeIdentifier(textContentType) {
handleText(content: content, attachment: attachment, index: index)
} else if attachment.hasItemConformingToTypeIdentifier(fileURLType) {
handleFiles(content: content, attachment: attachment, index: index)
} else if attachment.hasItemConformingToTypeIdentifier(urlContentType) {
handleUrl(content: content, attachment: attachment, index: index)
} else if attachment.hasItemConformingToTypeIdentifier(videoContentType) {
handleVideos(content: content, attachment: attachment, index: index)
}
}
}
}
}
override func didSelectPost() {
print("didSelectPost");
}
override func configurationItems() -> [Any]! {
// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
return []
}
private func handleText (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
attachment.loadItem(forTypeIdentifier: textContentType, options: nil) { [weak self] data, error in
if error == nil, let item = data as? String, let this = self {
this.sharedText.append(item)
// If this is the last item, save imagesData in userDefaults and redirect to host app
if index == (content.attachments?.count)! - 1 {
let userDefaults = UserDefaults(suiteName: "group.\(this.hostAppBundleIdentifier)")
userDefaults?.set(this.sharedText, forKey: this.sharedKey)
userDefaults?.synchronize()
this.redirectToHostApp(type: .text)
}
} else {
self?.dismissWithError()
}
}
}
private func handleUrl (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
attachment.loadItem(forTypeIdentifier: urlContentType, options: nil) { [weak self] data, error in
if error == nil, let item = data as? URL, let this = self {
this.sharedText.append(item.absoluteString)
// If this is the last item, save imagesData in userDefaults and redirect to host app
if index == (content.attachments?.count)! - 1 {
let userDefaults = UserDefaults(suiteName: "group.\(this.hostAppBundleIdentifier)")
userDefaults?.set(this.sharedText, forKey: this.sharedKey)
userDefaults?.synchronize()
this.redirectToHostApp(type: .text)
}
} else {
self?.dismissWithError()
}
}
}
private func handleImages (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
attachment.loadItem(forTypeIdentifier: imageContentType, options: nil) { [weak self] data, error in
if error == nil, let url = data as? URL, let this = self {
// Always copy
let fileName = this.getFileName(from: url, type: .image)
let newPath = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: "group.\(this.hostAppBundleIdentifier)")!
.appendingPathComponent(fileName)
let copied = this.copyFile(at: url, to: newPath)
if(copied) {
this.sharedMedia.append(SharedMediaFile(path: newPath.absoluteString, thumbnail: nil, duration: nil, type: .image))
}
// If this is the last item, save imagesData in userDefaults and redirect to host app
if index == (content.attachments?.count)! - 1 {
let userDefaults = UserDefaults(suiteName: "group.\(this.hostAppBundleIdentifier)")
userDefaults?.set(this.toData(data: this.sharedMedia), forKey: this.sharedKey)
userDefaults?.synchronize()
this.redirectToHostApp(type: .media)
}
} else {
self?.dismissWithError()
}
}
}
private func handleVideos (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
attachment.loadItem(forTypeIdentifier: videoContentType, options: nil) { [weak self] data, error in
if error == nil, let url = data as? URL, let this = self {
// Always copy
let fileName = this.getFileName(from: url, type: .video)
let newPath = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: "group.\(this.hostAppBundleIdentifier)")!
.appendingPathComponent(fileName)
let copied = this.copyFile(at: url, to: newPath)
if(copied) {
guard let sharedFile = this.getSharedMediaFile(forVideo: newPath) else {
return
}
this.sharedMedia.append(sharedFile)
}
// If this is the last item, save imagesData in userDefaults and redirect to host app
if index == (content.attachments?.count)! - 1 {
let userDefaults = UserDefaults(suiteName: "group.\(this.hostAppBundleIdentifier)")
userDefaults?.set(this.toData(data: this.sharedMedia), forKey: this.sharedKey)
userDefaults?.synchronize()
this.redirectToHostApp(type: .media)
}
} else {
self?.dismissWithError()
}
}
}
private func handleFiles (content: NSExtensionItem, attachment: NSItemProvider, index: Int) {
attachment.loadItem(forTypeIdentifier: fileURLType, options: nil) { [weak self] data, error in
if error == nil, let url = data as? URL, let this = self {
// Always copy
let fileName = this.getFileName(from :url, type: .file)
let newPath = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: "group.\(this.hostAppBundleIdentifier)")!
.appendingPathComponent(fileName)
let copied = this.copyFile(at: url, to: newPath)
if (copied) {
this.sharedMedia.append(SharedMediaFile(path: newPath.absoluteString, thumbnail: nil, duration: nil, type: .file))
}
if index == (content.attachments?.count)! - 1 {
let userDefaults = UserDefaults(suiteName: "group.\(this.hostAppBundleIdentifier)")
userDefaults?.set(this.toData(data: this.sharedMedia), forKey: this.sharedKey)
userDefaults?.synchronize()
this.redirectToHostApp(type: .file)
}
} else {
self?.dismissWithError()
}
}
}
private func dismissWithError() {
print("[ERROR] Error loading data!")
let alert = UIAlertController(title: "Error", message: "Error loading data", preferredStyle: .alert)
let action = UIAlertAction(title: "Error", style: .cancel) { _ in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
private func redirectToHostApp(type: RedirectType) {
let url = URL(string: "ShareMedia://dataUrl=\(sharedKey)#\(type)")
var responder = self as UIResponder?
let selectorOpenURL = sel_registerName("openURL:")
while (responder != nil) {
if (responder?.responds(to: selectorOpenURL))! {
let _ = responder?.perform(selectorOpenURL, with: url)
}
responder = responder!.next
}
extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
enum RedirectType {
case media
case text
case file
}
func getExtension(from url: URL, type: SharedMediaType) -> String {
let parts = url.lastPathComponent.components(separatedBy: ".")
var ex: String? = nil
if (parts.count > 1) {
ex = parts.last
}
if (ex == nil) {
switch type {
case .image:
ex = "PNG"
case .video:
ex = "MP4"
case .file:
ex = "TXT"
}
}
return ex ?? "Unknown"
}
func getFileName(from url: URL, type: SharedMediaType) -> String {
var name = url.lastPathComponent
if (name.isEmpty) {
name = UUID().uuidString + "." + getExtension(from: url, type: type)
}
return name
}
func copyFile(at srcURL: URL, to dstURL: URL) -> Bool {
do {
if FileManager.default.fileExists(atPath: dstURL.path) {
try FileManager.default.removeItem(at: dstURL)
}
try FileManager.default.copyItem(at: srcURL, to: dstURL)
} catch (let error) {
print("Cannot copy item at \(srcURL) to \(dstURL): \(error)")
return false
}
return true
}
private func getSharedMediaFile(forVideo: URL) -> SharedMediaFile? {
let asset = AVAsset(url: forVideo)
let duration = (CMTimeGetSeconds(asset.duration) * 1000).rounded()
let thumbnailPath = getThumbnailPath(for: forVideo)
if FileManager.default.fileExists(atPath: thumbnailPath.path) {
return SharedMediaFile(path: forVideo.absoluteString, thumbnail: thumbnailPath.absoluteString, duration: duration, type: .video)
}
var saved = false
let assetImgGenerate = AVAssetImageGenerator(asset: asset)
assetImgGenerate.appliesPreferredTrackTransform = true
// let scale = UIScreen.main.scale
assetImgGenerate.maximumSize = CGSize(width: 360, height: 360)
do {
let img = try assetImgGenerate.copyCGImage(at: CMTimeMakeWithSeconds(600, preferredTimescale: Int32(1.0)), actualTime: nil)
try UIImage.pngData(UIImage(cgImage: img))()?.write(to: thumbnailPath)
saved = true
} catch {
saved = false
}
return saved ? SharedMediaFile(path: forVideo.absoluteString, thumbnail: thumbnailPath.absoluteString, duration: duration, type: .video) : nil
}
private func getThumbnailPath(for url: URL) -> URL {
let fileName = Data(url.lastPathComponent.utf8).base64EncodedString().replacingOccurrences(of: "==", with: "")
let path = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: "group.\(hostAppBundleIdentifier)")!
.appendingPathComponent("\(fileName).jpg")
return path
}
class SharedMediaFile: Codable {
var path: String; // can be image, video or url path. It can also be text content
var thumbnail: String?; // video thumbnail
var duration: Double?; // video duration in milliseconds
var type: SharedMediaType;
init(path: String, thumbnail: String?, duration: Double?, type: SharedMediaType) {
self.path = path
self.thumbnail = thumbnail
self.duration = duration
self.type = type
}
// Debug method to print out SharedMediaFile details in the console
func toString() {
print("[SharedMediaFile] \n\tpath: \(self.path)\n\tthumbnail: \(self.thumbnail)\n\tduration: \(self.duration)\n\ttype: \(self.type)")
}
}
enum SharedMediaType: Int, Codable {
case image
case video
case file
}
func toData(data: [SharedMediaFile]) -> Data {
let encodedData = try? JSONEncoder().encode(data)
return encodedData!
}
}
extension Array {
subscript (safe index: UInt) -> Element? {
return Int(index) < count ? self[Int(index)] : nil
}
}

View File

@ -89,6 +89,8 @@ class CommentsCubit extends Cubit<CommentsState> {
Future<void> refresh() async {
final bool offlineReading = await _cacheRepository.hasCachedStories;
_cacheService.resetCollapsedComments();
if (offlineReading) {
emit(
state.copyWith(

View File

@ -52,6 +52,8 @@ class PinCubit extends Cubit<PinState> {
_preferenceRepository.updatePinnedStoriesIds(state.pinnedStoriesIds);
}
void refresh() => init();
void _onStoryFetched(Story story) {
emit(state.copyWith(pinnedStories: <Story>[...state.pinnedStories, story]));
}

View File

@ -10,23 +10,30 @@ part 'poll_state.dart';
class PollCubit extends Cubit<PollState> {
PollCubit({
required Story story,
StoriesRepository? storiesRepository,
}) : _storiesRepository =
}) : _story = story,
_storiesRepository =
storiesRepository ?? locator.get<StoriesRepository>(),
super(PollState.init());
final StoriesRepository _storiesRepository;
final Story _story;
Future<void> init({
required Story story,
bool refresh = false,
}) async {
if (refresh) {
emit(PollState.init());
}
emit(state.copyWith(status: PollStatus.loading));
List<int> pollOptionsIds = story.parts;
List<int> pollOptionsIds = _story.parts;
if (pollOptionsIds.isEmpty) {
if (pollOptionsIds.isEmpty || refresh) {
final Story? updatedStory =
await _storiesRepository.fetchStoryBy(story.id);
await _storiesRepository.fetchStoryBy(_story.id);
if (updatedStory != null) {
pollOptionsIds = updatedStory.parts;
@ -69,13 +76,7 @@ class PollCubit extends Cubit<PollState> {
}
}
void select(int id) {
emit(state.copyWith(selections: <int>{...state.selections, id}));
}
void unselect(int id) {
emit(state.copyWith(selections: <int>{...state.selections}..remove(id)));
}
void refresh() => init(refresh: true);
double _calculateRatio(int totalVotes, int votes) =>
totalVotes == 0 ? 0 : votes / totalVotes;

View File

@ -31,6 +31,8 @@ class PreferenceCubit extends Cubit<PreferenceState> {
.then((bool value) => emit(state.copyWith(useReader: value)));
_preferenceRepository.markReadStories
.then((bool value) => emit(state.copyWith(markReadStories: value)));
_preferenceRepository.shouldShowMetadata
.then((bool value) => emit(state.copyWith(showMetadata: value)));
}
void toggleNotificationMode() {
@ -67,4 +69,9 @@ class PreferenceCubit extends Cubit<PreferenceState> {
emit(state.copyWith(markReadStories: !state.markReadStories));
_preferenceRepository.toggleMarkReadStoriesMode();
}
void toggleMetadataMode() {
emit(state.copyWith(showMetadata: !state.showMetadata));
_preferenceRepository.toggleMetadataMode();
}
}

View File

@ -9,6 +9,7 @@ class PreferenceState extends Equatable {
required this.useTrueDark,
required this.useReader,
required this.markReadStories,
required this.showMetadata,
});
const PreferenceState.init()
@ -18,7 +19,8 @@ class PreferenceState extends Equatable {
showEyeCandy = false,
useTrueDark = false,
useReader = false,
markReadStories = false;
markReadStories = false,
showMetadata = false;
final bool showNotification;
final bool showComplexStoryTile;
@ -27,6 +29,7 @@ class PreferenceState extends Equatable {
final bool useTrueDark;
final bool useReader;
final bool markReadStories;
final bool showMetadata;
PreferenceState copyWith({
bool? showNotification,
@ -36,6 +39,7 @@ class PreferenceState extends Equatable {
bool? useTrueDark,
bool? useReader,
bool? markReadStories,
bool? showMetadata,
}) {
return PreferenceState(
showNotification: showNotification ?? this.showNotification,
@ -45,6 +49,7 @@ class PreferenceState extends Equatable {
useTrueDark: useTrueDark ?? this.useTrueDark,
useReader: useReader ?? this.useReader,
markReadStories: markReadStories ?? this.markReadStories,
showMetadata: showMetadata ?? this.showMetadata,
);
}
@ -57,5 +62,6 @@ class PreferenceState extends Equatable {
useTrueDark,
useReader,
markReadStories,
showMetadata,
];
}

View File

@ -3,4 +3,5 @@ export 'int_extension.dart';
export 'list_extension.dart';
export 'object_extension.dart';
export 'state_extension.dart';
export 'string_extension.dart';
export 'widget_extension.dart';

View File

@ -0,0 +1,14 @@
extension StringExtension on String {
int? getItemId() {
final RegExp regex = RegExp(r'\d+$');
final String match = regex.stringMatch(this) ?? '';
return int.tryParse(match);
}
String removeAllEmojis() {
final RegExp regex = RegExp(
r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])',
);
return replaceAllMapped(regex, (_) => '');
}
}

View File

@ -76,6 +76,7 @@ Future<void> main() async {
// runApp(
// HackiApp(
// savedThemeMode: savedThemeMode,
// trueDarkMode: trueDarkMode,
// ),
// );
// },

View File

@ -4,11 +4,15 @@ import 'package:hacki/extensions/extensions.dart';
import 'package:hacki/models/item.dart';
enum StoryType {
top,
latest,
ask,
show,
jobs,
top('topstories'),
latest('newstories'),
ask('askstories'),
show('showstories'),
jobs('jobstories');
const StoryType(this.path);
final String path;
}
class Story extends Item {
@ -66,6 +70,12 @@ class Story extends Item {
parent: 0,
);
String get metadata =>
'''$score point${score > 1 ? 's' : ''} by $by $postedDate | $descendants comment${descendants > 1 ? 's' : ''}''';
String get simpleMetadata =>
'''$score point${score > 1 ? 's' : ''} $descendants comment${descendants > 1 ? 's' : ''} $postedDate''';
String get postedDate =>
DateTime.fromMillisecondsSinceEpoch(time * 1000).toReadableString();

View File

@ -1,25 +1,23 @@
import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:hacki/config/locator.dart';
import 'package:hacki/models/models.dart';
import 'package:hacki/repositories/postable_repository.dart';
import 'package:hacki/repositories/repositories.dart';
import 'package:hacki/utils/service_exception.dart';
class AuthRepository {
class AuthRepository extends PostableRepository {
AuthRepository({
Dio? dio,
PreferenceRepository? preferenceRepository,
}) : _dio = dio ?? Dio(),
_preferenceRepository =
preferenceRepository ?? locator.get<PreferenceRepository>();
}) : _preferenceRepository =
preferenceRepository ?? locator.get<PreferenceRepository>(),
super(dio: dio);
final PreferenceRepository _preferenceRepository;
static const String _authority = 'news.ycombinator.com';
final Dio _dio;
final PreferenceRepository _preferenceRepository;
Future<bool> get loggedIn async => _preferenceRepository.loggedIn;
Future<String?> get username async => _preferenceRepository.username;
@ -37,7 +35,7 @@ class AuthRepository {
goto: 'news',
);
final bool success = await _performDefaultPost(uri, data);
final bool success = await performDefaultPost(uri, data);
if (success) {
await _preferenceRepository.setAuth(
@ -69,7 +67,7 @@ class AuthRepository {
un: flag ? null : 't',
);
return _performDefaultPost(uri, data);
return performDefaultPost(uri, data);
}
Future<bool> favorite({
@ -86,7 +84,7 @@ class AuthRepository {
un: favorite ? null : 't',
);
return _performDefaultPost(uri, data);
return performDefaultPost(uri, data);
}
Future<bool> upvote({
@ -103,7 +101,7 @@ class AuthRepository {
how: upvote ? 'up' : 'un',
);
return _performDefaultPost(uri, data);
return performDefaultPost(uri, data);
}
Future<bool> downvote({
@ -120,53 +118,6 @@ class AuthRepository {
how: downvote ? 'down' : 'un',
);
return _performDefaultPost(uri, data);
}
Future<bool> _performDefaultPost(
Uri uri,
PostDataMixin data, {
String? cookie,
bool Function(String?)? validateLocation,
}) async {
try {
final Response<void> response = await _performPost<void>(
uri,
data,
cookie: cookie,
validateStatus: (int? status) => status == HttpStatus.found,
);
if (validateLocation != null) {
return validateLocation(response.headers.value('location'));
}
return true;
} on ServiceException {
return false;
}
}
Future<Response<T>> _performPost<T>(
Uri uri,
PostDataMixin data, {
String? cookie,
ResponseType? responseType,
bool Function(int?)? validateStatus,
}) async {
try {
return await _dio.postUri<T>(
uri,
data: data.toJson(),
options: Options(
headers: <String, dynamic>{if (cookie != null) 'cookie': cookie},
responseType: responseType,
contentType: 'application/x-www-form-urlencoded',
validateStatus: validateStatus,
),
);
} on DioError catch (e) {
throw ServiceException(e.message);
}
return performDefaultPost(uri, data);
}
}

View File

@ -3,20 +3,20 @@ import 'dart:io';
import 'package:dio/dio.dart';
import 'package:hacki/config/locator.dart';
import 'package:hacki/models/post_data.dart';
import 'package:hacki/repositories/repositories.dart';
import 'package:hacki/repositories/postable_repository.dart';
import 'package:hacki/repositories/preference_repository.dart';
import 'package:hacki/utils/utils.dart';
class PostRepository {
class PostRepository extends PostableRepository {
PostRepository({Dio? dio, PreferenceRepository? storageRepository})
: _dio = dio ?? Dio(),
_preferenceRepository =
storageRepository ?? locator.get<PreferenceRepository>();
: _preferenceRepository =
storageRepository ?? locator.get<PreferenceRepository>(),
super(dio: dio);
final PreferenceRepository _preferenceRepository;
static const String _authority = 'news.ycombinator.com';
final Dio _dio;
final PreferenceRepository _preferenceRepository;
Future<bool> comment({
required int parentId,
required String text,
@ -36,7 +36,7 @@ class PostRepository {
text: text,
);
return _performDefaultPost(
return performDefaultPost(
uri,
data,
validateLocation: (String? location) => location == '/',
@ -79,7 +79,7 @@ class PostRepository {
text: text,
);
return _performDefaultPost(
return performDefaultPost(
uri,
data,
cookie: cookie,
@ -121,7 +121,7 @@ class PostRepository {
text: text,
);
return _performDefaultPost(
return performDefaultPost(
uri,
data,
cookie: cookie,
@ -144,58 +144,11 @@ class PostRepository {
pw: password,
id: id,
);
return _performPost(
return performPost(
uri,
data,
responseType: ResponseType.bytes,
validateStatus: (int? status) => status == HttpStatus.ok,
);
}
Future<bool> _performDefaultPost(
Uri uri,
PostDataMixin data, {
String? cookie,
bool Function(String?)? validateLocation,
}) async {
try {
final Response<void> response = await _performPost<void>(
uri,
data,
cookie: cookie,
validateStatus: (int? status) => status == HttpStatus.found,
);
if (validateLocation != null) {
return validateLocation(response.headers.value('location'));
}
return true;
} on ServiceException {
return false;
}
}
Future<Response<T>> _performPost<T>(
Uri uri,
PostDataMixin data, {
String? cookie,
ResponseType? responseType,
bool Function(int?)? validateStatus,
}) async {
try {
return await _dio.postUri<T>(
uri,
data: data.toJson(),
options: Options(
headers: <String, dynamic>{if (cookie != null) 'cookie': cookie},
responseType: responseType,
contentType: 'application/x-www-form-urlencoded',
validateStatus: validateStatus,
),
);
} on DioError catch (e) {
throw ServiceException(e.message);
}
}
}

View File

@ -0,0 +1,63 @@
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:hacki/models/models.dart';
import 'package:hacki/utils/service_exception.dart';
class PostableRepository {
PostableRepository({
Dio? dio,
}) : _dio = dio ?? Dio();
final Dio _dio;
@protected
Future<bool> performDefaultPost(
Uri uri,
PostDataMixin data, {
String? cookie,
bool Function(String?)? validateLocation,
}) async {
try {
final Response<void> response = await performPost<void>(
uri,
data,
cookie: cookie,
validateStatus: (int? status) => status == HttpStatus.found,
);
if (validateLocation != null) {
return validateLocation(response.headers.value('location'));
}
return true;
} on ServiceException {
return false;
}
}
@protected
Future<Response<T>> performPost<T>(
Uri uri,
PostDataMixin data, {
String? cookie,
ResponseType? responseType,
bool Function(int?)? validateStatus,
}) async {
try {
return await _dio.postUri<T>(
uri,
data: data.toJson(),
options: Options(
headers: <String, dynamic>{if (cookie != null) 'cookie': cookie},
responseType: responseType,
contentType: 'application/x-www-form-urlencoded',
validateStatus: validateStatus,
),
);
} on DioError catch (e) {
throw ServiceException(e.message);
}
}
}

View File

@ -21,6 +21,7 @@ class PreferenceRepository {
static const String _unreadCommentsIdsKey = 'unreadCommentsIds';
static const String _lastReadStoryIdKey = 'lastReadStoryId';
static const String _isFirstLaunchKey = 'isFirstLaunch';
static const String _metadataModeKey = 'metadataMode';
static const String _notificationModeKey = 'notificationMode';
static const String _readerModeKey = 'readerMode';
@ -46,6 +47,7 @@ class PreferenceRepository {
static const bool _readerModeDefaultValue = true;
static const bool _markReadStoriesModeDefaultValue = true;
static const bool _isFirstLaunchKeyDefaultValue = true;
static const bool _metadataModeDefaultValue = true;
final SyncedSharedPreferences _syncedPrefs;
final Future<SharedPreferences> _prefs;
@ -67,29 +69,6 @@ class PreferenceRepository {
return val;
}
Future<List<String>> get blocklist async => _prefs.then(
(SharedPreferences prefs) =>
prefs.getStringList(_blocklistKey) ?? <String>[],
);
Future<List<int>> get pinnedStoriesIds async {
if (Platform.isIOS) {
final List<String>? favList = await _syncedPrefs.getStringList(
key: _pinnedStoriesIdsKey,
);
return favList?.map(int.parse).toList() ?? <int>[];
} else {
return _prefs.then(
(SharedPreferences prefs) =>
prefs
.getStringList(_pinnedStoriesIdsKey)
?.map(int.parse)
.toList() ??
<int>[],
);
}
}
Future<bool> get shouldShowNotification async => _prefs.then(
(SharedPreferences prefs) =>
prefs.getBool(_notificationModeKey) ??
@ -111,6 +90,11 @@ class PreferenceRepository {
prefs.getBool(_eyeCandyModeKey) ?? _eyeCandyModeDefaultValue,
);
Future<bool> get shouldShowMetadata async => _prefs.then(
(SharedPreferences prefs) =>
prefs.getBool(_metadataModeKey) ?? _metadataModeDefaultValue,
);
Future<bool> get trueDarkMode async => _prefs.then(
(SharedPreferences prefs) =>
prefs.getBool(trueDarkModeKey) ?? _trueDarkModeDefaultValue,
@ -127,24 +111,6 @@ class PreferenceRepository {
_markReadStoriesModeDefaultValue,
);
Future<List<int>> get unreadCommentsIds async => _prefs.then(
(SharedPreferences prefs) =>
prefs
.getStringList(_unreadCommentsIdsKey)
?.map(int.parse)
.toList() ??
<int>[],
);
Future<int?> get lastReadStoryId async =>
_prefs.then((SharedPreferences prefs) {
final String? val = prefs.getString(_lastReadStoryIdKey);
if (val == null) return null;
return int.tryParse(val);
});
Future<bool> hasPushed(int commentId) async =>
_prefs.then((SharedPreferences prefs) {
final bool? val = prefs.getBool(_getPushNotificationKey(commentId));
@ -170,53 +136,6 @@ class PreferenceRepository {
}
}
Future<List<int>> favList({required String of}) async {
final SharedPreferences prefs = await _prefs;
if (Platform.isIOS) {
final List<String> previousList =
((prefs.getStringList(_getFavKey('')) ?? <String>[])
..addAll(prefs.getStringList(_getFavKey(of)) ?? <String>[]))
.toList();
/// Since v0.2.5, fav list will be stored in [NSUbiquitousKeyValueStore]
/// instead of [UserDefaults] on iOS.
if (previousList.isNotEmpty) {
for (final String fav in previousList) {
await addFav(username: of, id: int.parse(fav));
}
await prefs.remove(_getFavKey(''));
await prefs.remove(_getFavKey(of));
}
final List<String>? initialList =
await _syncedPrefs.getStringList(key: _getFavKey(''));
final List<String>? userList =
await _syncedPrefs.getStringList(key: _getFavKey(of));
return <String>{
...?initialList,
...?userList,
}.map(int.parse).toList();
} else {
final List<int> favList =
((prefs.getStringList(_getFavKey('')) ?? <String>[])
..addAll(prefs.getStringList(_getFavKey(of)) ?? <String>[]))
.map(int.parse)
.toSet()
.toList();
return favList;
}
}
Future<bool?> vote({required int submittedTo, required String from}) async {
final SharedPreferences prefs = await _prefs;
final String key = _getVoteKey(from, submittedTo);
final bool? vote = prefs.getBool(key);
return vote;
}
Future<void> setAuth({
required String username,
required String password,
@ -279,6 +198,55 @@ class PreferenceRepository {
await prefs.setBool(_markReadStoriesModeKey, !currentMode);
}
Future<void> toggleMetadataMode() async {
final SharedPreferences prefs = await _prefs;
final bool currentMode =
prefs.getBool(_metadataModeKey) ?? _metadataModeDefaultValue;
await prefs.setBool(_metadataModeKey, !currentMode);
}
//#region fav
Future<List<int>> favList({required String of}) async {
final SharedPreferences prefs = await _prefs;
if (Platform.isIOS) {
final List<String> previousList =
((prefs.getStringList(_getFavKey('')) ?? <String>[])
..addAll(prefs.getStringList(_getFavKey(of)) ?? <String>[]))
.toList();
/// Since v0.2.5, fav list will be stored in [NSUbiquitousKeyValueStore]
/// instead of [UserDefaults] on iOS.
if (previousList.isNotEmpty) {
for (final String fav in previousList) {
await addFav(username: of, id: int.parse(fav));
}
await prefs.remove(_getFavKey(''));
await prefs.remove(_getFavKey(of));
}
final List<String>? initialList =
await _syncedPrefs.getStringList(key: _getFavKey(''));
final List<String>? userList =
await _syncedPrefs.getStringList(key: _getFavKey(of));
return <String>{
...?initialList,
...?userList,
}.map(int.parse).toList();
} else {
final List<int> favList =
((prefs.getStringList(_getFavKey('')) ?? <String>[])
..addAll(prefs.getStringList(_getFavKey(of)) ?? <String>[]))
.map(int.parse)
.toSet()
.toList();
return favList;
}
}
Future<void> addFav({required String username, required int id}) async {
final String key = _getFavKey(username);
@ -331,6 +299,19 @@ class PreferenceRepository {
}
}
static String _getFavKey(String username) => 'fav_$username';
//#endregion
//#region vote
Future<bool?> vote({required int submittedTo, required String from}) async {
final SharedPreferences prefs = await _prefs;
final String key = _getVoteKey(from, submittedTo);
final bool? vote = prefs.getBool(key);
return vote;
}
Future<void> addVote({
required String username,
required int id,
@ -350,11 +331,44 @@ class PreferenceRepository {
await prefs.remove(key);
}
String _getVoteKey(String username, int id) => 'vote_$username-$id';
//#endregion
//#region blocklist
Future<List<String>> get blocklist async => _prefs.then(
(SharedPreferences prefs) =>
prefs.getStringList(_blocklistKey) ?? <String>[],
);
Future<void> updateBlocklist(List<String> usernames) async {
final SharedPreferences prefs = await _prefs;
await prefs.setStringList(_blocklistKey, usernames);
}
//#endregion
//#region pins
Future<List<int>> get pinnedStoriesIds async {
if (Platform.isIOS) {
final List<String>? favList = await _syncedPrefs.getStringList(
key: _pinnedStoriesIdsKey,
);
return favList?.map(int.parse).toList() ?? <int>[];
} else {
return _prefs.then(
(SharedPreferences prefs) =>
prefs
.getStringList(_pinnedStoriesIdsKey)
?.map(int.parse)
.toList() ??
<int>[],
);
}
}
Future<void> updatePinnedStoriesIds(List<int> ids) async {
if (Platform.isIOS) {
await _syncedPrefs.setStringList(
@ -370,6 +384,19 @@ class PreferenceRepository {
}
}
//#endregion
//#region unread comment ids
Future<List<int>> get unreadCommentsIds async => _prefs.then(
(SharedPreferences prefs) =>
prefs
.getStringList(_unreadCommentsIdsKey)
?.map(int.parse)
.toList() ??
<int>[],
);
Future<void> updateUnreadCommentsIds(List<int> ids) async {
final SharedPreferences prefs = await _prefs;
await prefs.setStringList(
@ -378,6 +405,19 @@ class PreferenceRepository {
);
}
//#endregion
//#region reminder
Future<int?> get lastReadStoryId async =>
_prefs.then((SharedPreferences prefs) {
final String? val = prefs.getString(_lastReadStoryIdKey);
if (val == null) return null;
return int.tryParse(val);
});
Future<void> updateLastReadStoryId(int? id) async {
final SharedPreferences prefs = await _prefs;
await prefs.setString(
@ -386,6 +426,8 @@ class PreferenceRepository {
);
}
//#endregion
Future<void> updateHasPushed(int commentId) async {
final SharedPreferences prefs = await _prefs;
await prefs.setBool(
@ -422,11 +464,7 @@ class PreferenceRepository {
}
}
String _getPushNotificationKey(int commentId) => 'pushed_$commentId';
static String _getPushNotificationKey(int commentId) => 'pushed_$commentId';
String _getFavKey(String username) => 'fav_$username';
String _getVoteKey(String username, int id) => 'vote_$username-$id';
String _getHasReadKey(int storyId) => 'hasRead_$storyId';
static String _getHasReadKey(int storyId) => 'hasRead_$storyId';
}

View File

@ -28,6 +28,8 @@ class SearchRepository {
final String by = hit['author'] as String? ?? '';
final String title = hit['title'] as String? ?? '';
final int createdAt = hit['created_at_i'] as int? ?? 0;
final int score = hit['points'] as int? ?? 0;
final int descendants = hit['num_comments'] as int? ?? 0;
// Getting rid of comments, only keeping stories for convenience.
// Don't judge me.
@ -46,9 +48,9 @@ class SearchRepository {
final int id = int.parse(hit['objectID'] as String? ?? '0');
final Story story = Story(
descendants: 0,
descendants: descendants,
id: id,
score: 0,
score: score,
time: createdAt,
by: by,
title: title,

View File

@ -25,22 +25,9 @@ class StoriesRepository {
}
Future<List<int>> fetchStoryIds({required StoryType of}) async {
final String suffix = () {
switch (of) {
case StoryType.top:
return 'topstories.json';
case StoryType.latest:
return 'newstories.json';
case StoryType.ask:
return 'askstories.json';
case StoryType.show:
return 'showstories.json';
case StoryType.jobs:
return 'jobstories.json';
}
}();
final List<int> ids =
await _firebaseClient.get('$_baseUrl$suffix').then((dynamic val) {
final List<int> ids = await _firebaseClient
.get('$_baseUrl${of.path}.json')
.then((dynamic val) {
final List<int> ids = (val as List<dynamic>).cast<int>();
return ids;
});

View File

@ -23,6 +23,7 @@ import 'package:hacki/screens/screens.dart';
import 'package:hacki/screens/widgets/widgets.dart';
import 'package:hacki/services/services.dart';
import 'package:hacki/utils/utils.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'package:responsive_builder/responsive_builder.dart';
class HomeScreen extends StatefulWidget {
@ -49,6 +50,9 @@ class _HomeScreenState extends State<HomeScreen>
);
late final TabController tabController;
late final StreamSubscription<String> intentDataStreamSubscription;
late final StreamSubscription<String?> notificationStreamSubscription;
int currentIndex = 0;
static const Duration _throttleDelay = Duration(seconds: 1);
@ -74,32 +78,14 @@ class _HomeScreenState extends State<HomeScreen>
// Constants.featurePinToTop,
// ]);
ReceiveSharingIntent.getInitialText().then(onShareExtensionTapped);
intentDataStreamSubscription =
ReceiveSharingIntent.getTextStream().listen(onShareExtensionTapped);
if (!selectNotificationSubject.hasListener) {
selectNotificationSubject.stream.listen((String? payload) async {
if (payload == null) return;
final Map<String, dynamic> payloadJson =
jsonDecode(payload) as Map<String, dynamic>;
final int? storyId = payloadJson['storyId'] as int?;
final int? commentId = payloadJson['commentId'] as int?;
if (storyId != null && commentId != null) {
context.read<NotificationCubit>().markAsRead(commentId);
await locator
.get<StoriesRepository>()
.fetchStoryBy(storyId)
.then((Story? story) {
if (story == null) {
showSnackBar(content: 'Something went wrong...');
return;
}
final StoryScreenArgs args = StoryScreenArgs(story: story);
goToStoryScreen(args: args);
});
}
});
notificationStreamSubscription =
selectNotificationSubject.stream.listen(onNotificationTapped);
}
SchedulerBinding.instance
@ -140,12 +126,22 @@ class _HomeScreenState extends State<HomeScreen>
}
}
@override
void dispose() {
featureDiscoveryDismissThrottle.dispose();
tabController.dispose();
intentDataStreamSubscription.cancel();
notificationStreamSubscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final BlocBuilder<PreferenceCubit, PreferenceState> homeScreen =
BlocBuilder<PreferenceCubit, PreferenceState>(
buildWhen: (PreferenceState previous, PreferenceState current) =>
previous.showComplexStoryTile != current.showComplexStoryTile,
previous.showComplexStoryTile != current.showComplexStoryTile ||
previous.showMetadata != current.showMetadata,
builder: (BuildContext context, PreferenceState preferenceState) {
final BlocBuilder<PinCubit, PinState> pinnedStories =
BlocBuilder<PinCubit, PinState>(
@ -177,8 +173,9 @@ class _HomeScreenState extends State<HomeScreen>
child: StoryTile(
key: ObjectKey(story),
story: story,
onTap: () => onStoryTapped(story),
onTap: () => onStoryTapped(story, isPin: true),
showWebPreview: preferenceState.showComplexStoryTile,
showMetadata: preferenceState.showMetadata,
),
),
),
@ -413,13 +410,13 @@ class _HomeScreenState extends State<HomeScreen>
return Future<bool>.value(false);
}
void onStoryTapped(Story story) {
void onStoryTapped(Story story, {bool isPin = false}) {
final bool showWebFirst =
context.read<PreferenceCubit>().state.showWebFirst;
final bool useReader = context.read<PreferenceCubit>().state.useReader;
final bool offlineReading =
context.read<StoriesBloc>().state.offlineReading;
final bool hasRead = context.read<StoriesBloc>().hasRead(story);
final bool hasRead = isPin || context.read<StoriesBloc>().hasRead(story);
final bool splitViewEnabled = context.read<SplitViewCubit>().state.enabled;
// If a story is a job story and it has a link to the job posting,
@ -467,6 +464,51 @@ class _HomeScreenState extends State<HomeScreen>
),
);
}
void onShareExtensionTapped(String? event) {
if (event == null) return;
final int? id = event.getItemId();
if (id != null) {
locator
.get<StoriesRepository>()
.fetchParentStory(id: id)
.then((Story? story) {
if (mounted) {
if (story != null) {
goToStoryScreen(args: StoryScreenArgs(story: story));
}
}
});
}
}
Future<void> onNotificationTapped(String? payload) async {
if (payload == null) return;
final Map<String, dynamic> payloadJson =
jsonDecode(payload) as Map<String, dynamic>;
final int? storyId = payloadJson['storyId'] as int?;
final int? commentId = payloadJson['commentId'] as int?;
if (storyId != null && commentId != null) {
context.read<NotificationCubit>().markAsRead(commentId);
await locator
.get<StoriesRepository>()
.fetchStoryBy(storyId)
.then((Story? story) {
if (story == null) {
showSnackBar(content: 'Something went wrong...');
return;
}
final StoryScreenArgs args = StoryScreenArgs(story: story);
goToStoryScreen(args: args);
});
}
}
}
class _MobileHomeScreenBuilder extends StatelessWidget {

View File

@ -119,6 +119,7 @@ class _ProfileScreenState extends State<ProfileScreen>
return ItemsListView<Item>(
showWebPreview: false,
showMetadata: false,
useConsistentFontSize: true,
refreshController: refreshControllerHistory,
items: historyState.submittedItems
@ -170,6 +171,7 @@ class _ProfileScreenState extends State<ProfileScreen>
return ItemsListView<Story>(
showWebPreview:
preferenceState.showComplexStoryTile,
showMetadata: preferenceState.showMetadata,
refreshController: refreshControllerFav,
items: favState.favStories,
onRefresh: () {
@ -292,6 +294,21 @@ class _ProfileScreenState extends State<ProfileScreen>
},
activeColor: Colors.orange,
),
SwitchListTile(
title: const Text('Show Metadata'),
subtitle: const Text(
'show number of comments and post date'
' in story tile.',
),
value: preferenceState.showMetadata,
onChanged: (bool val) {
HapticFeedback.lightImpact();
context
.read<PreferenceCubit>()
.toggleMetadataMode();
},
activeColor: Colors.orange,
),
SwitchListTile(
title: const Text('Show Web Page First'),
subtitle: const Text(
@ -390,7 +407,7 @@ class _ProfileScreenState extends State<ProfileScreen>
showAboutDialog(
context: context,
applicationName: 'Hacki',
applicationVersion: 'v0.2.7',
applicationVersion: 'v0.2.12',
applicationIcon: ClipRRect(
borderRadius: const BorderRadius.all(
Radius.circular(12),

View File

@ -48,20 +48,14 @@ class InboxView extends StatelessWidget {
loadStyle: LoadStyle.ShowWhenLoading,
builder: (BuildContext context, LoadStatus? mode) {
Widget body;
if (mode == LoadStatus.idle) {
body = const Text('');
} else if (mode == LoadStatus.loading) {
if (mode == LoadStatus.loading) {
body = const CustomCircularProgressIndicator();
} else if (mode == LoadStatus.failed) {
body = const Text(
'loading failed.',
);
} else if (mode == LoadStatus.canLoading) {
body = const Text(
'loading more.',
);
} else {
body = const Text('');
body = const SizedBox.shrink();
}
return SizedBox(
height: 55,

View File

@ -73,20 +73,14 @@ class _SearchScreenState extends State<SearchScreen> {
loadStyle: LoadStyle.ShowWhenLoading,
builder: (BuildContext context, LoadStatus? mode) {
Widget body;
if (mode == LoadStatus.idle) {
body = const Text('');
} else if (mode == LoadStatus.loading) {
if (mode == LoadStatus.loading) {
body = const CustomCircularProgressIndicator();
} else if (mode == LoadStatus.failed) {
body = const Text(
'loading failed.',
);
} else if (mode == LoadStatus.canLoading) {
body = const Text(
'loading more.',
);
} else {
body = const Text('');
body = const SizedBox.shrink();
}
return SizedBox(
height: 55,
@ -108,6 +102,7 @@ class _SearchScreenState extends State<SearchScreen> {
child: StoryTile(
showWebPreview:
prefState.showComplexStoryTile,
showMetadata: prefState.showMetadata,
story: e,
onTap: () => goToStoryScreen(
args: StoryScreenArgs(story: e),

View File

@ -77,7 +77,7 @@ class StoryScreen extends StatefulWidget {
if (args.story.isPoll)
BlocProvider<PollCubit>(
create: (BuildContext context) =>
PollCubit()..init(story: args.story),
PollCubit(story: args.story)..init(),
),
],
child: StoryScreen(
@ -104,7 +104,7 @@ class StoryScreen extends StatefulWidget {
if (args.story.isPoll)
BlocProvider<PollCubit>(
create: (BuildContext context) =>
PollCubit()..init(story: args.story),
PollCubit(story: args.story)..init(),
),
],
child: StoryScreen(
@ -261,6 +261,10 @@ class _StoryScreenState extends State<StoryScreen> {
HapticFeedback.lightImpact();
locator.get<CacheService>().resetComments();
context.read<CommentsCubit>().refresh();
if (widget.story.isPoll) {
context.read<PollCubit>().refresh();
}
},
onLoading: () {
context.read<CommentsCubit>().loadMore();
@ -388,7 +392,6 @@ class _StoryScreenState extends State<StoryScreen> {
),
if (widget.story.isPoll)
PollView(
story: widget.story,
onLoginTapped: onLoginTapped,
),
],
@ -653,9 +656,7 @@ class _StoryScreenState extends State<StoryScreen> {
}
Future<void> onStoryLinkTapped(String link) async {
final RegExp regex = RegExp(r'\d+$');
final String match = regex.stringMatch(link) ?? '';
final int? id = int.tryParse(match);
final int? id = link.getItemId();
if (id != null) {
storyLinkTapThrottle.run(() {
locator
@ -668,7 +669,7 @@ class _StoryScreenState extends State<StoryScreen> {
StoryScreen.routeName,
arguments: StoryScreenArgs(story: story),
);
} else {}
}
}
});
});

View File

@ -9,11 +9,9 @@ import 'package:hacki/models/models.dart';
class PollView extends StatelessWidget {
const PollView({
super.key,
required this.story,
required this.onLoginTapped,
});
final Story story;
final VoidCallback onLoginTapped;
@override
@ -126,7 +124,7 @@ class PollView extends StatelessWidget {
option.text,
),
Text(
'${option.score} votes',
'''${option.score} vote${option.score > 1 ? 's' : ''}''',
style: const TextStyle(
color: Colors.grey,
fontSize: 12,

View File

@ -150,7 +150,21 @@ class CommentTile extends StatelessWidget {
],
),
),
if (comment.deleted)
if (actionable && state.collapsed)
Center(
child: Padding(
padding:
const EdgeInsets.only(bottom: 12),
child: Text(
'collapsed '
'(${state.collapsedCount + 1})',
style: const TextStyle(
color: Colors.orangeAccent,
),
),
),
)
else if (comment.deleted)
const Center(
child: Padding(
padding: EdgeInsets.only(bottom: 12),
@ -187,20 +201,6 @@ class CommentTile extends StatelessWidget {
),
),
)
else if (actionable && state.collapsed)
Center(
child: Padding(
padding:
const EdgeInsets.only(bottom: 12),
child: Text(
'collapsed '
'(${state.collapsedCount + 1})',
style: const TextStyle(
color: Colors.orangeAccent,
),
),
),
)
else
Padding(
padding: const EdgeInsets.only(

View File

@ -14,6 +14,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
const ItemsListView({
super.key,
required this.showWebPreview,
required this.showMetadata,
required this.items,
required this.onTap,
required this.refreshController,
@ -32,6 +33,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
);
final bool showWebPreview;
final bool showMetadata;
final bool enablePullDown;
final bool markReadStories;
final bool showOfflineBanner;
@ -44,7 +46,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
final List<T> items;
final Widget? header;
final RefreshController? refreshController;
final RefreshController refreshController;
final VoidCallback? onRefresh;
final VoidCallback? onLoadMore;
final ValueChanged<Story>? onPinned;
@ -89,6 +91,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
story: e,
onTap: () => onTap(e),
showWebPreview: showWebPreview,
showMetadata: showMetadata,
hasRead: markReadStories && hasRead,
simpleTileFontSize: useConsistentFontSize ? 14 : 16,
),
@ -180,10 +183,6 @@ class ItemsListView<T extends Item> extends StatelessWidget {
],
);
if (refreshController == null) {
return child;
}
return SmartRefresher(
enablePullUp: true,
enablePullDown: enablePullDown,
@ -194,20 +193,14 @@ class ItemsListView<T extends Item> extends StatelessWidget {
loadStyle: LoadStyle.ShowWhenLoading,
builder: (BuildContext context, LoadStatus? mode) {
Widget body;
if (mode == LoadStatus.idle) {
body = const Text('');
} else if (mode == LoadStatus.loading) {
if (mode == LoadStatus.loading) {
body = const CustomCircularProgressIndicator();
} else if (mode == LoadStatus.failed) {
body = const Text(
'loading failed.',
);
} else if (mode == LoadStatus.canLoading) {
body = const Text(
'loading more.',
);
} else {
body = const Text('');
body = const SizedBox.shrink();
}
return SizedBox(
height: 55,
@ -215,7 +208,7 @@ class ItemsListView<T extends Item> extends StatelessWidget {
);
},
),
controller: refreshController!,
controller: refreshController,
onRefresh: onRefresh,
onLoading: onLoadMore,
child: child,

View File

@ -3,6 +3,7 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:hacki/config/constants.dart';
import 'package:hacki/models/models.dart';
import 'package:hacki/screens/widgets/link_preview/link_view.dart';
import 'package:hacki/screens/widgets/link_preview/web_analyzer.dart';
import 'package:url_launcher/url_launcher.dart';
@ -11,6 +12,8 @@ class LinkPreview extends StatefulWidget {
const LinkPreview({
super.key,
required this.link,
required this.story,
required this.showMetadata,
this.cache = const Duration(days: 30),
this.titleStyle,
this.bodyStyle,
@ -28,6 +31,8 @@ class LinkPreview extends StatefulWidget {
this.removeElevation = false,
});
final Story story;
/// Web address (Url that need to be parsed)
/// For IOS & Web, only HTTP and HTTPS are support
/// For Android, all urls are supported
@ -95,18 +100,19 @@ class LinkPreview extends StatefulWidget {
/// `[BoxShadow(blurRadius: 3, color: Colors.grey)]`
final List<BoxShadow>? boxShadow;
final bool showMetadata;
@override
_LinkPreviewState createState() => _LinkPreviewState();
}
class _LinkPreviewState extends State<LinkPreview> {
InfoBase? _info;
String? _errorImage, _errorTitle, _errorBody, _url;
String? _errorTitle, _errorBody, _url;
bool _loading = false;
@override
void initState() {
_errorImage = widget.errorImage ?? Constants.hackerNewsLogoLink;
_errorTitle = widget.errorTitle ?? 'Something went wrong!';
_errorBody = widget.errorBody ??
'Oops! Unable to parse the url. We have '
@ -114,7 +120,12 @@ class _LinkPreviewState extends State<LinkPreview> {
'we will try to fix this in our next release. Thanks!';
_url = widget.link.trim();
_info = WebAnalyzer.getInfoFromCache(_url);
if (_url?.isNotEmpty ?? false) {
_info = WebAnalyzer.getInfoFromCache(_url);
} else {
_info = WebAnalyzer.getInfoFromCache(widget.story.id.toString());
}
if (_info == null) {
_loading = true;
_getInfo();
@ -124,14 +135,23 @@ class _LinkPreviewState extends State<LinkPreview> {
Future<void> _getInfo() async {
if (_url!.startsWith('http') || _url!.startsWith('https')) {
_info = await WebAnalyzer.getInfo(_url, cache: widget.cache);
if (mounted) {
setState(() {
_loading = false;
});
}
_info = await WebAnalyzer.getInfo(
_url,
story: widget.story,
cache: widget.cache,
);
} else {
//print('$_url is not starting with either http or https');
_info = await WebAnalyzer.getInfo(
widget.story.id.toString(),
story: widget.story,
cache: widget.cache,
);
}
if (mounted) {
setState(() {
_loading = false;
});
}
}
@ -167,10 +187,12 @@ class _LinkPreviewState extends State<LinkPreview> {
height: _height,
child: LinkView(
key: widget.key ?? Key(widget.link),
metadata: widget.story.simpleMetadata,
url: widget.link,
title: title!,
description: desc!,
imageUri: imageUri,
imagePath: Constants.hackerNewsLogoPath,
onTap: _launchURL,
titleTextStyle: widget.titleStyle,
bodyTextStyle: widget.bodyStyle,
@ -180,6 +202,7 @@ class _LinkPreviewState extends State<LinkPreview> {
isIcon: isIcon,
bgColor: widget.backgroundColor,
radius: widget.borderRadius ?? 12,
showMetadata: widget.showMetadata,
),
);
}
@ -212,9 +235,8 @@ class _LinkPreviewState extends State<LinkPreview> {
_height,
title: _errorTitle,
desc: _errorBody,
imageUri: widget.showMultimedia
? (img.trim() == '' ? _errorImage : img)
: null,
imageUri:
widget.showMultimedia ? (img.trim() == '' ? null : img) : null,
);
} else {
final WebInfo? info = _info as WebInfo?;
@ -222,7 +244,8 @@ class _LinkPreviewState extends State<LinkPreview> {
? _buildLinkContainer(
_height,
title: _errorTitle,
imageUri: widget.showMultimedia ? _errorImage : null,
desc: _errorBody,
imageUri: null,
)
: _buildLinkContainer(
_height,
@ -235,7 +258,7 @@ class _LinkPreviewState extends State<LinkPreview> {
? info.image
: WebAnalyzer.isNotEmpty(info.icon)
? info.icon
: _errorImage)
: null)
: null,
isIcon: !WebAnalyzer.isNotEmpty(info.image),
);

View File

@ -5,10 +5,12 @@ import 'package:hacki/config/constants.dart';
class LinkView extends StatelessWidget {
const LinkView({
super.key,
required this.metadata,
required this.url,
required this.title,
required this.description,
required this.onTap,
required this.showMetadata,
this.imageUri,
this.imagePath,
this.titleTextStyle,
@ -25,6 +27,7 @@ class LinkView extends StatelessWidget {
'imageUri or imagePath cannot be null when showMultiMedia is true',
);
final String metadata;
final String url;
final String title;
final String description;
@ -39,6 +42,7 @@ class LinkView extends StatelessWidget {
final bool isIcon;
final double radius;
final Color? bgColor;
final bool showMetadata;
double computeTitleFontSize(double width) {
double size = width * 0.13;
@ -97,7 +101,7 @@ class LinkView extends StatelessWidget {
child: (imageUri?.isEmpty ?? true) && imagePath != null
? Image.asset(
imagePath!,
fit: isIcon ? BoxFit.scaleDown : BoxFit.fitWidth,
fit: BoxFit.cover,
)
: CachedNetworkImage(
imageUrl: imageUri!,
@ -166,6 +170,20 @@ class LinkView extends StatelessWidget {
padding: const EdgeInsets.fromLTRB(5, 3, 5, 0),
child: Column(
children: <Widget>[
if (showMetadata)
Container(
alignment: Alignment.topLeft,
child: Text(
metadata,
textAlign: TextAlign.left,
style: _bodyTS.copyWith(
fontSize:
_bodyTS.fontSize == null ? 12 : _bodyTS.fontSize! - 2,
),
overflow: bodyTextOverflow ?? TextOverflow.ellipsis,
maxLines: 1,
),
),
Expanded(
child: Container(
alignment: Alignment.topLeft,
@ -174,7 +192,8 @@ class LinkView extends StatelessWidget {
textAlign: TextAlign.left,
style: _bodyTS,
overflow: bodyTextOverflow ?? TextOverflow.ellipsis,
maxLines: bodyMaxLines ?? _maxLines,
maxLines:
(bodyMaxLines ?? _maxLines) - (showMetadata ? 1 : 0),
),
),
),

View File

@ -5,7 +5,11 @@ import 'dart:io';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:fast_gbk/fast_gbk.dart';
import 'package:flutter/foundation.dart';
import 'package:html/dom.dart' hide Text;
import 'package:hacki/config/locator.dart';
import 'package:hacki/extensions/extensions.dart';
import 'package:hacki/models/models.dart';
import 'package:hacki/repositories/repositories.dart';
import 'package:html/dom.dart' hide Text, Comment;
import 'package:html/parser.dart' as parser;
import 'package:http/http.dart';
import 'package:http/io_client.dart';
@ -63,7 +67,7 @@ class WebVideoInfo extends WebImageInfo {
/// Web analyzer
class WebAnalyzer {
static final Map<String?, InfoBase> _map = <String?, InfoBase>{};
static final Map<String?, InfoBase> cacheMap = <String?, InfoBase>{};
static final RegExp _bodyReg =
RegExp(r'<body[^>]*>([\s\S]*?)<\/body>', caseSensitive: false);
static final RegExp _htmlReg = RegExp(
@ -80,7 +84,10 @@ class WebAnalyzer {
static final RegExp _lineReg = RegExp(r'[\n\r]|&nbsp;|&gt;');
static final RegExp _spaceReg = RegExp(r'\s+');
/// Is it an empty string
static bool isEmpty(String? str) {
return !isNotEmpty(str);
}
static bool isNotEmpty(String? str) {
return str != null && str.isNotEmpty && str.trim().isNotEmpty;
}
@ -88,10 +95,11 @@ class WebAnalyzer {
/// Get web information
/// return [InfoBase]
static InfoBase? getInfoFromCache(String? url) {
final InfoBase? info = _map[url];
final InfoBase? info = cacheMap[url];
if (info != null) {
if (!info._timeout.isAfter(DateTime.now())) {
_map.remove(url);
cacheMap.remove(url);
}
}
return info;
@ -101,25 +109,69 @@ class WebAnalyzer {
/// return [InfoBase]
static Future<InfoBase?> getInfo(
String? url, {
required Story story,
Duration cache = const Duration(hours: 24),
bool multimedia = true,
}) async {
// final start = DateTime.now();
InfoBase? info = getInfoFromCache(url);
if (info != null) return info;
if (story.url.isEmpty && story.text.isNotEmpty) {
info = WebInfo(
title: story.title,
description: story.text,
).._timeout = DateTime.now().add(cache);
cacheMap[story.id.toString()] = info;
return info;
}
try {
info = await _getInfoByIsolate(url, multimedia);
if (info != null) {
info._timeout = DateTime.now().add(cache);
_map[url] = info;
cacheMap[url] = info;
}
} catch (e) {
//print('Get web error:$url, Error:$e');
//locator.get<Logger>().log(Level.error, e);
}
// print("$url cost ${DateTime.now().difference(start).inMilliseconds}");
if ((info == null ||
info is WebImageInfo ||
(info is WebInfo && (info.description?.isEmpty ?? true))) &&
story.kids.isNotEmpty) {
bool shouldRetry = false;
final Comment? comment = await locator
.get<StoriesRepository>()
.fetchCommentBy(id: story.kids.first)
.catchError((Object err) async {
int index = 0;
Comment? comment;
while (comment == null && index < story.kids.length) {
comment = await locator
.get<CacheRepository>()
.getCachedComment(id: story.kids.elementAt(index));
index++;
}
shouldRetry = true;
return comment;
});
info = WebInfo(
description:
comment != null ? '${comment.by}: ${comment.text}' : 'no comments',
image: info is WebInfo ? info.image : (info as WebImageInfo?)?.image,
icon: info is WebInfo ? info.icon : null,
);
if (!shouldRetry) {
info._timeout = DateTime.now().add(cache);
cacheMap[url] = info;
}
}
return info;
}
@ -128,6 +180,7 @@ class WebAnalyzer {
final Response? response = await _requestUrl(url);
if (response == null) return null;
if (multimedia!) {
final String? contentType = response.headers['content-type'];
if (contentType != null) {
@ -156,7 +209,8 @@ class WebAnalyzer {
if (res[0] == '0') {
info = WebInfo(
title: res[1] as String?,
description: res[2] as String?,
description:
res[2] == null ? null : (res[2] as String).removeAllEmojis(),
icon: res[3] as String?,
image: res[4] as String?,
);
@ -214,17 +268,21 @@ class WebAnalyzer {
..maxRedirects = 3
..persistentConnection = true
..headers['accept-encoding'] = 'gzip, deflate'
..headers['User-Agent'] =
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36'
..headers['User-Agent'] = url.contains('twitter.com')
? 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
: 'Mozilla/5.0'
..headers['cache-control'] = 'no-cache'
..headers['accept'] =
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9';
// print(request.headers);
final IOStreamedResponse stream =
await client.send(request).catchError((dynamic err) {
//print('Error in getting the link => ${request.url}');
//print('Error => $err');
// locator.get<Logger>().log(
// Level.error,
// 'Error in getting the link => ${request.url}\n$err',
// );
});
if (stream.statusCode == HttpStatus.movedTemporarily ||
stream.statusCode == HttpStatus.movedPermanently) {
if (stream.isRedirect && count < 6) {
@ -240,7 +298,6 @@ class WebAnalyzer {
}
count++;
client.close();
// print("Redirect ====> $url");
return _requestUrl(url, count: count, cookie: cookie);
}
} else if (stream.statusCode == HttpStatus.ok) {
@ -257,7 +314,6 @@ class WebAnalyzer {
}
}
client.close();
//if (res == null) print('Get web info empty($url)');
return res;
}
@ -274,28 +330,22 @@ class WebAnalyzer {
String temp = html.replaceAll(r'\', '');
temp = temp.replaceAll('u003C', '<');
temp = temp.replaceAll('u003E', '>');
// print(temp);
} else {
// print(html);
}
} catch (e) {
try {
html = gbk.decode(response.bodyBytes);
} catch (e) {
//print('Web page resolution failure from:$url Error:$e');
// locator.get<Logger>().log(
// Level.error,
// 'Web page resolution failure from:$url Error:$e',
// );
}
}
if (html == null) {
//print('Web page resolution failure from:$url');
return null;
}
if (html == null) return null;
// Improved performance
// final start = DateTime.now();
final String headHtml = _getHeadHtml(html);
final Document document = parser.parse(headHtml);
// print("dom cost ${DateTime.now().difference(start).inMilliseconds}");
final Uri uri = Uri.parse(url);
// get image or video
@ -360,6 +410,7 @@ class WebAnalyzer {
static String _analyzeTitle(Document document, {bool isTwitter = false}) {
if (isTwitter) return '';
final String? title = _getMetaContent(document, 'property', 'og:title');
if (title != null) return title;
final List<Element> list = document.head!.getElementsByTagName('title');
if (list.isNotEmpty) {
@ -379,14 +430,12 @@ class WebAnalyzer {
_getMetaContent(document, 'name', 'description') ??
_getMetaContent(document, 'name', 'Description');
if (!isNotEmpty(description)) {
// final DateTime start = DateTime.now();
if (isEmpty(description)) {
String body = html.replaceAll(_htmlReg, '');
body = body.trim().replaceAll(_lineReg, ' ').replaceAll(_spaceReg, ' ');
if (body.length > 300) {
body = body.substring(0, 300);
}
// print("html cost ${DateTime.now().difference(start).inMilliseconds}");
if (body.contains('JavaScript is disabled in your browser')) return '';
return body;
}

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hacki/blocs/blocs.dart';
import 'package:hacki/cubits/cubits.dart';
import 'package:hacki/screens/widgets/link_preview/web_analyzer.dart';
class OfflineBanner extends StatelessWidget {
const OfflineBanner({
@ -57,6 +58,7 @@ class OfflineBanner extends StatelessWidget {
context.read<StoriesBloc>().add(StoriesExitOffline());
context.read<AuthBloc>().add(AuthInitialize());
context.read<PinCubit>().init();
WebAnalyzer.cacheMap.clear();
}
});
},

View File

@ -40,7 +40,8 @@ class _StoriesListViewState extends State<StoriesListView> {
return BlocBuilder<PreferenceCubit, PreferenceState>(
buildWhen: (PreferenceState previous, PreferenceState current) =>
previous.showComplexStoryTile != current.showComplexStoryTile,
previous.showComplexStoryTile != current.showComplexStoryTile ||
previous.showMetadata != current.showMetadata,
builder: (BuildContext context, PreferenceState preferenceState) {
return BlocConsumer<StoriesBloc, StoriesState>(
listenWhen: (StoriesState previous, StoriesState current) =>
@ -66,6 +67,7 @@ class _StoriesListViewState extends State<StoriesListView> {
markReadStories:
context.read<PreferenceCubit>().state.markReadStories,
showWebPreview: preferenceState.showComplexStoryTile,
showMetadata: preferenceState.showMetadata,
refreshController: refreshController,
items: state.storiesByType[storyType]!,
onRefresh: () {
@ -73,6 +75,7 @@ class _StoriesListViewState extends State<StoriesListView> {
context
.read<StoriesBloc>()
.add(StoriesRefresh(type: storyType));
context.read<PinCubit>().refresh();
},
onLoadMore: () {
context

View File

@ -4,9 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_fadein/flutter_fadein.dart';
import 'package:hacki/config/constants.dart';
import 'package:hacki/models/models.dart';
import 'package:hacki/screens/widgets/link_preview/link_view.dart';
import 'package:hacki/screens/widgets/widgets.dart';
import 'package:html/parser.dart';
import 'package:shimmer/shimmer.dart';
class StoryTile extends StatelessWidget {
@ -14,12 +12,14 @@ class StoryTile extends StatelessWidget {
super.key,
this.hasRead = false,
required this.showWebPreview,
required this.showMetadata,
required this.story,
required this.onTap,
this.simpleTileFontSize = 16,
});
final bool showWebPreview;
final bool showMetadata;
final bool hasRead;
final Story story;
final VoidCallback onTap;
@ -35,137 +35,107 @@ class StoryTile extends StatelessWidget {
? 100.0
: (MediaQuery.of(context).size.height * 0.14).clamp(118.0, 140.0);
if (story.url.isNotEmpty) {
return TapDownWrapper(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
),
child: AbsorbPointer(
child: LinkPreview(
link: story.url.isNotEmpty ? story.url : 's',
placeholderWidget: FadeIn(
child: SizedBox(
height: height,
child: Shimmer.fromColors(
baseColor: Colors.orange,
highlightColor: Colors.orangeAccent,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
right: 5,
bottom: 5,
top: 5,
),
child: Container(
height: height,
width: height,
color: Colors.white,
return TapDownWrapper(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
),
child: AbsorbPointer(
child: LinkPreview(
story: story,
link: story.url,
placeholderWidget: FadeIn(
child: SizedBox(
height: height,
child: Shimmer.fromColors(
baseColor: Colors.orange,
highlightColor: Colors.orangeAccent,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
right: 5,
bottom: 5,
top: 5,
),
child: Container(
height: height,
width: height,
color: Colors.white,
),
),
Expanded(
flex: 4,
child: Padding(
padding: const EdgeInsets.only(left: 4, top: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: double.infinity,
height: 14,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 4),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: 40,
height: 10,
color: Colors.white,
),
],
),
),
Expanded(
flex: 4,
child: Padding(
padding: const EdgeInsets.only(left: 4, top: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: double.infinity,
height: 14,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 4),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: double.infinity,
height: 10,
color: Colors.white,
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 3),
),
Container(
width: 40,
height: 10,
color: Colors.white,
),
],
),
),
)
],
),
)
],
),
),
),
errorImage: Constants.hackerNewsLogoLink,
backgroundColor: Colors.transparent,
borderRadius: 0,
removeElevation: true,
bodyMaxLines: height == 100 ? 3 : 4,
errorTitle: story.title,
titleStyle: TextStyle(
color: hasRead
? Colors.grey[500]
: Theme.of(context).textTheme.subtitle1!.color,
fontWeight: FontWeight.bold,
),
),
errorImage: Constants.hackerNewsLogoLink,
backgroundColor: Colors.transparent,
borderRadius: 0,
removeElevation: true,
bodyMaxLines: height == 100 ? 3 : 4,
errorTitle: story.title,
titleStyle: TextStyle(
color: hasRead
? Colors.grey[500]
: Theme.of(context).textTheme.subtitle1!.color,
fontWeight: FontWeight.bold,
),
showMetadata: showMetadata,
),
),
);
} else {
final String text = parse(story.text).body?.text ?? '';
return TapDownWrapper(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
),
child: AbsorbPointer(
child: SizedBox(
height: height,
child: LinkView(
title: story.title,
description: text,
onTap: (_) {},
url: '',
imagePath: Constants.hackerNewsLogoPath,
bodyMaxLines: height == 100 ? 3 : 4,
titleTextStyle: TextStyle(
color: hasRead
? Colors.grey[500]
: Theme.of(context).textTheme.subtitle1!.color,
fontWeight: FontWeight.bold,
),
),
),
),
),
);
}
),
);
} else {
return InkWell(
onTap: onTap,
@ -190,6 +160,21 @@ class StoryTile extends StatelessWidget {
),
],
),
if (showMetadata)
Row(
children: <Widget>[
Expanded(
child: Text(
story.metadata,
style: TextStyle(
color: Colors.grey,
fontSize: simpleTileFontSize - 2,
),
maxLines: 1,
),
),
],
),
const SizedBox(
height: 8,
),

View File

@ -2,9 +2,7 @@ import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' as parser;
import 'package:html_unescape/html_unescape.dart';
class HtmlUtil {
const HtmlUtil._();
abstract class HtmlUtil {
static String? getTitle(dynamic input) =>
parser.parse(input).head?.querySelector('title')?.text;

View File

@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';
class LinkUtil {
abstract class LinkUtil {
static final ChromeSafariBrowser _browser = ChromeSafariBrowser();
static void launchUrl(String link, {bool useReader = false}) {

View File

@ -776,6 +776,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.0"
receive_sharing_intent:
dependency: "direct main"
description:
name: receive_sharing_intent
url: "https://pub.dartlang.org"
source: hosted
version: "1.4.5"
responsive_builder:
dependency: "direct main"
description:

Some files were not shown because too many files have changed in this diff Show More