Compare commits

...

3 Commits

Author SHA1 Message Date
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
24 changed files with 344 additions and 356 deletions

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

@ -568,7 +568,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@ -577,7 +577,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.2.8;
MARKETING_VERSION = 0.2.10;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@ -705,7 +705,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@ -714,7 +714,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.2.8;
MARKETING_VERSION = 0.2.10;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@ -736,7 +736,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = QMWX3X2NF7;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@ -745,7 +745,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 0.2.8;
MARKETING_VERSION = 0.2.10;
PRODUCT_BUNDLE_IDENTIFIER = com.jiaqi.hacki;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";

View File

@ -23,6 +23,10 @@ class PollCubit extends Cubit<PollState> {
Future<void> init({
bool refresh = false,
}) async {
if (refresh) {
emit(PollState.init());
}
emit(state.copyWith(status: PollStatus.loading));
List<int> pollOptionsIds = _story.parts;

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 {

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

@ -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

@ -390,7 +390,7 @@ class _ProfileScreenState extends State<ProfileScreen>
showAboutDialog(
context: context,
applicationName: 'Hacki',
applicationVersion: 'v0.2.8',
applicationVersion: 'v0.2.10',
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,

View File

@ -261,7 +261,10 @@ class _StoryScreenState extends State<StoryScreen> {
HapticFeedback.lightImpact();
locator.get<CacheService>().resetComments();
context.read<CommentsCubit>().refresh();
context.read<PollCubit>().refresh();
if (widget.story.isPoll) {
context.read<PollCubit>().refresh();
}
},
onLoading: () {
context.read<CommentsCubit>().loadMore();

View File

@ -44,7 +44,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;
@ -180,10 +180,6 @@ class ItemsListView<T extends Item> extends StatelessWidget {
],
);
if (refreshController == null) {
return child;
}
return SmartRefresher(
enablePullUp: true,
enablePullDown: enablePullDown,
@ -194,20 +190,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 +205,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,7 @@ class LinkPreview extends StatefulWidget {
const LinkPreview({
super.key,
required this.link,
required this.story,
this.cache = const Duration(days: 30),
this.titleStyle,
this.bodyStyle,
@ -28,6 +30,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
@ -101,12 +105,11 @@ class LinkPreview extends StatefulWidget {
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 +117,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 +132,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;
});
}
}
@ -171,6 +188,7 @@ class _LinkPreviewState extends State<LinkPreview> {
title: title!,
description: desc!,
imageUri: imageUri,
imagePath: Constants.hackerNewsLogoPath,
onTap: _launchURL,
titleTextStyle: widget.titleStyle,
bodyTextStyle: widget.bodyStyle,
@ -212,9 +230,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 +239,8 @@ class _LinkPreviewState extends State<LinkPreview> {
? _buildLinkContainer(
_height,
title: _errorTitle,
imageUri: widget.showMultimedia ? _errorImage : null,
desc: _errorBody,
imageUri: null,
)
: _buildLinkContainer(
_height,
@ -235,7 +253,7 @@ class _LinkPreviewState extends State<LinkPreview> {
? info.image
: WebAnalyzer.isNotEmpty(info.icon)
? info.icon
: _errorImage)
: null)
: null,
isIcon: !WebAnalyzer.isNotEmpty(info.image),
);

View File

@ -97,7 +97,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!,

View File

@ -5,7 +5,10 @@ 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/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 +66,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 +83,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 +94,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 +108,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 +179,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) {
@ -214,17 +266,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 +296,6 @@ class WebAnalyzer {
}
count++;
client.close();
// print("Redirect ====> $url");
return _requestUrl(url, count: count, cookie: cookie);
}
} else if (stream.statusCode == HttpStatus.ok) {
@ -257,7 +312,6 @@ class WebAnalyzer {
}
}
client.close();
//if (res == null) print('Get web info empty($url)');
return res;
}
@ -274,28 +328,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 +408,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 +428,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

@ -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 {
@ -35,137 +33,106 @@ 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,
),
),
),
);
} 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,

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

@ -1,6 +1,6 @@
name: hacki
description: A Hacker News reader.
version: 0.2.8+45
version: 0.2.10+48
publish_to: none
environment: