repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/getter_utils.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/reddit.dart';
abstract class GetterUtils {
static DateTime? dateTimeOrNull(double? time) {
if (time == null) {
return null;
}
return DateTime.fromMillisecondsSinceEpoch(time.round() * 1000,
isUtc: true);
}
static DateTime? dateTimeOrNullFromString(String? time) {
if (time == null) {
return null;
}
return DateTime.parse(time);
}
static RedditorRef? redditorRefOrNull(Reddit reddit, String? redditor) =>
(redditor == null) ? null : reddit.redditor(redditor);
static SubredditRef? subredditRefOrNull(Reddit reddit, String? subreddit) =>
(subreddit == null) ? null : reddit.subreddit(subreddit);
static Uri? uriOrNull(String? uri) => (uri == null) ? null : Uri.parse(uri);
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/platform_utils_unsupported.dart | /// Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
class Platform {
static bool get isAndroid => false;
static bool get isFuchsia => false;
static bool get isIOS => false;
static bool get isLinux => false;
static bool get isMacOS => false;
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/util.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/models/subreddit.dart';
/// A set that can only contain up to a max number of elements. If the set is
/// full and another item is added, the oldest item in the set is removed.
class BoundedSet<T> {
final int _maxItems;
final List _fifo;
final Set _set;
BoundedSet(int maxItems)
: _maxItems = maxItems,
_fifo = <T>[],
_set = <T>{};
bool contains(T object) {
return _set.contains(object);
}
void add(T object) {
if (_set.length == _maxItems) {
final success = _set.remove(_fifo.removeAt(0));
assert(success);
}
_fifo.add(object);
_set.add(object);
}
}
/// A counter class which increases count exponentially with jitter up to a
/// maximum value.
class ExponentialCounter {
final double _maxCounter;
final Random _random;
double _base = 1.0;
ExponentialCounter(int maxCounter)
: _maxCounter = maxCounter.toDouble(),
_random = Random();
int counter() {
// See the following for a description of jitter and why we should use it:
// https://www.awsarchitectureblog.com/2015/03/backoff.html
final maxJitter = _base / 16.0;
final value = _base + _random.nextDouble() * maxJitter - maxJitter / 2.0;
_base = min(_base * 2, _maxCounter);
return value.round();
}
void reset() {
_base = 1.0;
}
}
Stream<T?> streamGenerator<T>(function,
{int? itemLimit, int? pauseAfter}) async* {
final counter = ExponentialCounter(16);
final BoundedSet<String?> seen = BoundedSet<String>(301);
var withoutBeforeCounter = 0;
var responsesWithoutNew = 0;
var beforeFullname;
var count = 0;
while (true) {
var limit = 100;
var found = false;
var newestFullname;
if (beforeFullname == null) {
limit -= withoutBeforeCounter;
withoutBeforeCounter = (withoutBeforeCounter + 1) % 30;
}
final results = [];
await for (final item in function(params: <String, String>{
'limit': min(limit, itemLimit ?? limit).toString(),
if (beforeFullname != null) 'before': beforeFullname,
})) {
results.add(item);
}
for (final item in results.reversed) {
final fullname = await item.fullname;
if (seen.contains(fullname)) {
continue;
}
found = true;
seen.add(fullname);
newestFullname = fullname;
yield item as T;
count++;
if (itemLimit == count) {
return;
}
}
beforeFullname = newestFullname;
if (pauseAfter != null && pauseAfter < 0) {
yield null;
} else if (found) {
counter.reset();
responsesWithoutNew = 0;
} else {
responsesWithoutNew += 1;
if (pauseAfter != null && (responsesWithoutNew > pauseAfter)) {
responsesWithoutNew = 0;
yield null;
} else {
await Future.delayed(Duration(seconds: counter.counter()));
}
}
}
}
Map<String, dynamic> snakeCaseMapKeys(Map<String, dynamic> m) =>
m.map((k, v) => MapEntry(snakeCase(k), v));
final RegExp _snakecaseRegexp = RegExp('[A-Z]');
String snakeCase(String name, [separator = '_']) => name.replaceAllMapped(
_snakecaseRegexp,
(Match match) =>
(match.start != 0 ? separator : '') + match.group(0)!.toLowerCase());
String permissionsString(
List<String> permissions, Set<String> validPermissions) {
final processed = <String>[];
if (permissions.isEmpty ||
((permissions.length == 1) && (permissions[0] == 'all'))) {
processed.add('+all');
} else {
//processed.add('-all');
final omitted = validPermissions.difference(permissions.toSet());
processed.addAll(omitted.map((s) => '-$s').toList());
processed.addAll(permissions.map((s) => '+$s').toList());
}
return processed.join(',');
}
ModeratorPermission stringToModeratorPermission(String p) {
switch (p) {
case 'all':
return ModeratorPermission.all;
case 'access':
return ModeratorPermission.access;
case 'config':
return ModeratorPermission.config;
case 'flair':
return ModeratorPermission.flair;
case 'mail':
return ModeratorPermission.mail;
case 'posts':
return ModeratorPermission.posts;
case 'wiki':
return ModeratorPermission.wiki;
default:
throw DRAWInternalError("Unknown moderator permission '$p'");
}
}
List<ModeratorPermission> stringsToModeratorPermissions(
List<String> permissions) =>
permissions.map((p) => stringToModeratorPermission(p)).toList();
String moderatorPermissionToString(ModeratorPermission p) {
switch (p) {
case ModeratorPermission.all:
return 'all';
case ModeratorPermission.access:
return 'access';
case ModeratorPermission.config:
return 'config';
case ModeratorPermission.flair:
return 'flair';
case ModeratorPermission.mail:
return 'mail';
case ModeratorPermission.posts:
return 'posts';
case ModeratorPermission.wiki:
return 'wiki';
default:
throw DRAWInternalError("Unknown ModeratorPermission '$p'");
}
}
List<String> moderatorPermissionsToStrings(
List<ModeratorPermission> permissions) =>
permissions.map((p) => moderatorPermissionToString(p)).toList();
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/reddit.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:draw/src/auth.dart';
import 'package:draw/src/draw_config_context.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/frontpage.dart';
import 'package:draw/src/models/comment.dart';
import 'package:draw/src/models/inbox.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/submission.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/models/subreddits.dart';
import 'package:draw/src/objector.dart';
import 'package:draw/src/user.dart';
import 'package:oauth2/oauth2.dart' as oauth2;
/// The [Reddit] class provides access to Reddit's API and stores session state
/// for the current [Reddit] instance. This class contains objects that can be
/// used to interact with Reddit posts, comments, subreddits, multireddits, and
/// users.
class Reddit {
///The default Url for the OAuthEndpoint
static final String defaultOAuthApiEndpoint = r'oauth.reddit.com';
/// The default object kind mapping for [Comment].
static final String defaultCommentKind = DRAWConfigContext.kCommentKind;
/// The default object kind mapping for [Message].
static final String defaultMessageKind = DRAWConfigContext.kMessageKind;
/// The default object kind mapping for [Redditor].
static final String defaultRedditorKind = DRAWConfigContext.kRedditorKind;
/// The default object kind mapping for [Submission].
static final String defaultSubmissionKind = DRAWConfigContext.kSubmissionKind;
/// The default object kind mapping for [Subreddit].
static final String defaultSubredditKind = DRAWConfigContext.kSubredditKind;
/// The default object kind mapping for [Trophy].
static final String defaultTrophyKind = DRAWConfigContext.kTrophyKind;
/// A flag representing whether or not this [Reddit] instance can only make
/// read requests.
bool get readOnly => _readOnly;
/// The authorized client used to interact with Reddit APIs.
Authenticator get auth => _auth;
/// Provides methods to retrieve content from the Reddit front page.
FrontPage get front => _front;
Inbox get inbox => _inbox;
/// Provides methods to interact with sets of subreddits.
Subreddits get subreddits => _subreddits;
/// Provides methods for the currently authenticated user.
User get user => _user;
/// The configuration for the current [Reddit] instance.
DRAWConfigContext get config => _config;
/// A utility class that converts Reddit API responses to DRAW objects.
Objector get objector => _objector;
late Authenticator _auth;
late DRAWConfigContext _config;
late FrontPage _front;
late Inbox _inbox;
late Subreddits _subreddits;
late User _user;
bool _readOnly = true;
bool _initialized = false;
final _initializedCompleter = Completer<bool>();
late Objector _objector;
/// Creates a new read-only [Reddit] instance for installed application types.
///
/// This method should be used to create a read-only instance in
/// circumstances where a client secret would not be secure.
///
/// [clientId] is the identifier associated with your authorized application
/// on Reddit. To get a client ID, create an authorized application
/// [here](http://www.reddit.com/prefs/apps).
///
/// [deviceId] is a unique ID per-device or per-user. See
/// [Application Only OAuth](https://github.com/reddit-archive/reddit/wiki/OAuth2#application-only-oauth)
/// for best practices regarding device IDs.
///
/// [userAgent] is an arbitrary identifier used by the Reddit API to
/// differentiate between client instances. This should be relatively unique.
///
/// [tokenEndpoint] is a [Uri] to an alternative token endpoint. If not
/// provided, [defaultTokenEndpoint] is used.
///
/// [authEndpoint] is a [Uri] to an alternative authentication endpoint. If not
/// provided, [defaultAuthTokenEndpoint] is used.
///
/// [configUri] is a [Uri] pointing to a 'draw.ini' file, which can be used to
/// populate the previously described parameters.
///
/// [siteName] is the name of the configuration to use from draw.ini. Defaults
/// to 'default'.
static Future<Reddit> createUntrustedReadOnlyInstance(
{String? clientId,
String? deviceId,
String? userAgent,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName = 'default'}) async {
final reddit = Reddit._untrustedReadOnlyInstance(clientId, deviceId,
userAgent, tokenEndpoint, authEndpoint, configUri, siteName);
final initialized = await reddit._initializedCompleter.future;
if (initialized) {
return reddit;
}
throw DRAWAuthenticationError(
'Unable to get valid OAuth token for read-only instance');
}
/// Creates a new [Reddit] instance for use with the installed application
/// authentication flow. This instance is not authenticated until a valid
/// response code is provided to `WebAuthenticator.authorize`
/// (see test/auth/web_auth.dart for an example usage).
///
/// [clientId] is the identifier associated with your authorized application
/// on Reddit. To get a client ID, create an authorized application
/// [here](http://www.reddit.com/prefs/apps).
///
/// [userAgent] is an arbitrary identifier used by the Reddit API to
/// differentiate between client instances. This should be relatively unique.
///
/// [redirectUri] is the redirect URI associated with your Reddit application.
///
/// [tokenEndpoint] is a [Uri] to an alternative token endpoint. If not
/// provided, [defaultTokenEndpoint] is used.
///
/// [authEndpoint] is a [Uri] to an alternative authentication endpoint. If not
/// provided, [defaultAuthTokenEndpoint] is used.
///
/// [configUri] is a [Uri] pointing to a 'draw.ini' file, which can be used to
/// populate the previously described parameters.
///
/// [siteName] is the name of the configuration to use from draw.ini. Defaults
/// to 'default'.
static Reddit createInstalledFlowInstance(
{String? clientId,
String? userAgent,
Uri? redirectUri,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName = 'default'}) =>
Reddit._webFlowInstance(clientId, '', userAgent, redirectUri,
tokenEndpoint, authEndpoint, configUri, siteName);
/// Creates a new read-only [Reddit] instance for web and script applications.
///
/// [clientId] is the identifier associated with your authorized application
/// on Reddit. To get a client ID, create an authorized application
/// [here](http://www.reddit.com/prefs/apps).
///
/// [clientSecret] is the unique secret associated with your client ID. This
/// is required for script and web applications.
///
/// [userAgent] is an arbitrary identifier used by the Reddit API to
/// differentiate between client instances. This should be relatively unique.
///
/// [tokenEndpoint] is a [Uri] to an alternative token endpoint. If not
/// provided, [defaultTokenEndpoint] is used.
///
/// [authEndpoint] is a [Uri] to an alternative authentication endpoint. If not
/// provided, [defaultAuthTokenEndpoint] is used.
///
/// [configUri] is a [Uri] pointing to a 'draw.ini' file, which can be used to
/// populate the previously described parameters.
///
/// [siteName] is the name of the configuration to use from draw.ini. Defaults
/// to 'default'.
static Future<Reddit> createReadOnlyInstance(
{String? clientId,
String? clientSecret,
String? userAgent,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName = 'default'}) async {
final reddit = Reddit._readOnlyInstance(clientId, clientSecret, userAgent,
tokenEndpoint, authEndpoint, configUri, siteName);
final initialized = await reddit._initializedCompleter.future;
if (initialized) {
return reddit;
}
throw DRAWAuthenticationError('Unable to authenticate with Reddit');
}
/// Creates a new authenticated [Reddit] instance for use with personal use
/// scripts.
///
/// [clientId] is the identifier associated with your authorized application
/// on Reddit. To get a client ID, create an authorized application
/// [here](http://www.reddit.com/prefs/apps).
///
/// [clientSecret] is the unique secret associated with your client ID. This
/// is required for script and web applications.
///
/// [userAgent] is an arbitrary identifier used by the Reddit API to
/// differentiate between client instances. This should be relatively unique.
///
/// [username] and [password] is a valid Reddit username password combination.
/// These fields are required in order to perform any account actions or make
/// posts.
///
/// [tokenEndpoint] is a [Uri] to an alternative token endpoint. If not
/// provided, [defaultTokenEndpoint] is used.
///
/// [authEndpoint] is a [Uri] to an alternative authentication endpoint. If not
/// provided, [defaultAuthTokenEndpoint] is used.
///
/// [configUri] is a [Uri] pointing to a 'draw.ini' file, which can be used to
/// populate the previously described parameters.
///
/// [siteName] is the name of the configuration to use from draw.ini. Defaults
/// to 'default'.
static Future<Reddit> createScriptInstance(
{String? clientId,
String? clientSecret,
String? userAgent,
String? username,
String? password,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName = 'default'}) async {
final reddit = Reddit._scriptInstance(clientId, clientSecret, userAgent,
username, password, tokenEndpoint, authEndpoint, configUri, siteName);
final initialized = await reddit._initializedCompleter.future;
if (initialized) {
return reddit;
}
throw DRAWAuthenticationError('Unable to authenticate with Reddit');
}
/// Creates a new [Reddit] instance for use with the web authentication flow.
/// This instance is not authenticated until a valid response code is
/// provided to `WebAuthenticator.authorize` (see test/auth/web_auth.dart
/// for an example usage).
///
/// [clientId] is the identifier associated with your authorized application
/// on Reddit. To get a client ID, create an authorized application
/// [here](http://www.reddit.com/prefs/apps).
///
/// [clientSecret] is the unique secret associated with your client ID. This
/// is required for script and web applications.
///
/// [userAgent] is an arbitrary identifier used by the Reddit API to
/// differentiate between client instances. This should be relatively unique.
///
/// [redirectUri] is the redirect URI associated with your Reddit application.
///
/// [tokenEndpoint] is a [Uri] to an alternative token endpoint. If not
/// provided, [defaultTokenEndpoint] is used.
///
/// [authEndpoint] is a [Uri] to an alternative authentication endpoint. If not
/// provided, [defaultAuthTokenEndpoint] is used.
///
/// [configUri] is a [Uri] pointing to a 'draw.ini' file, which can be used to
/// populate the previously described parameters.
///
/// [siteName] is the name of the configuration to use from draw.ini. Defaults
/// to 'default'.
static Reddit createWebFlowInstance(
{String? clientId,
String? clientSecret,
String? userAgent,
Uri? redirectUri,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName = 'default'}) =>
Reddit._webFlowInstance(clientId, clientSecret, userAgent, redirectUri,
tokenEndpoint, authEndpoint, configUri, siteName);
/// Creates a new [Reddit] instance for use with the web authentication flow.
/// This instance is not authenticated until a valid response code is
/// provided to `WebAuthenticator.authorize` (see test/auth/web_auth.dart
/// for an example usage).
///
/// [clientId] is the identifier associated with your authorized application
/// on Reddit. To get a client ID, create an authorized application
/// [here](http://www.reddit.com/prefs/apps).
///
/// [userAgent] is an arbitrary identifier used by the Reddit API to
/// differentiate between client instances. This should be relatively unique.
///
/// [redirectUri] is the redirect URI associated with your Reddit application.
///
/// [tokenEndpoint] is a [Uri] to an alternative token endpoint. If not
/// provided, [defaultTokenEndpoint] is used.
///
/// [authEndpoint] is a [Uri] to an alternative authentication endpoint. If not
/// provided, [defaultAuthTokenEndpoint] is used.
///
/// [configUri] is a [Uri] pointing to a 'draw.ini' file, which can be used to
/// populate the previously described parameters.
///
/// [siteName] is the name of the configuration to use from draw.ini. Defaults
/// to 'default'.
static Reddit restoreAuthenticatedInstance(String credentialsJson,
{String? clientId,
String? clientSecret,
String? userAgent,
Uri? redirectUri,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName = 'default'}) {
return Reddit._webFlowInstanceRestore(
clientId,
clientSecret,
userAgent,
credentialsJson,
redirectUri,
tokenEndpoint,
authEndpoint,
configUri,
siteName);
}
/// Creates a new installed [Reddit] instance from cached credentials.
///
/// [credentialsJson] is a json string containing the cached credentials. This
/// parameter is required and cannot be 'null'.
///
/// This string can be retrieved from an installed [Reddit] instance in
/// the following manner:
///
/// ```dart
/// final credentialsJson = reddit.auth.credentials.toJson();
/// ```
///
/// [clientId] is the identifier associated with your installed application
/// on Reddit. To get a client ID, create an installed application
/// [here](http://www.reddit.com/prefs/apps).
///
/// [userAgent] is an arbitrary identifier used by the Reddit API to
/// differentiate between client instances. This should be relatively unique.
///
/// [redirectUri] is the redirect URI associated with your Reddit application.
///
/// [tokenEndpoint] is a [Uri] to an alternative token endpoint. If not
/// provided, [defaultTokenEndpoint] is used.
///
/// [authEndpoint] is a [Uri] to an alternative authentication endpoint. If not
/// provided, [defaultAuthTokenEndpoint] is used.
///
/// [configUri] is a [Uri] pointing to a 'draw.ini' file, which can be used to
/// populate the previously described parameters.
///
/// [siteName] is the name of the configuration to use from draw.ini. Defaults
/// to 'default'.
static Reddit restoreInstalledAuthenticatedInstance(String credentialsJson,
{String? clientId,
String? clientSecret,
String? userAgent,
Uri? redirectUri,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName = 'default'}) {
return Reddit._webFlowInstanceRestore(
clientId,
'',
userAgent,
credentialsJson,
redirectUri,
tokenEndpoint,
authEndpoint,
configUri,
siteName);
}
Reddit._readOnlyInstance(
String? clientId,
String? clientSecret,
String? userAgent,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName) {
// Loading passed in values into config file.
_config = DRAWConfigContext(
clientId: clientId,
clientSecret: clientSecret,
userAgent: userAgent,
accessToken: tokenEndpoint.toString(),
authorizeUrl: authEndpoint.toString(),
configUrl: configUri.toString(),
siteName: siteName);
if (_config.userAgent == null) {
throw DRAWAuthenticationError('userAgent cannot be null.');
}
final grant = oauth2.AuthorizationCodeGrant(_config.clientId!,
Uri.parse(_config.authorizeUrl!), Uri.parse(_config.accessToken!),
secret: _config.clientSecret);
_readOnly = true;
ReadOnlyAuthenticator.create(_config, grant)
.then(_initializationCallback)
.catchError(_initializationError);
}
Reddit._untrustedReadOnlyInstance(
String? clientId,
String? deviceId,
String? userAgent,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName) {
// Loading passed in values into config file.
_config = DRAWConfigContext(
clientId: clientId,
clientSecret: '',
userAgent: userAgent,
accessToken: tokenEndpoint.toString(),
authorizeUrl: authEndpoint.toString(),
configUrl: configUri.toString(),
siteName: siteName);
if (_config.userAgent == null) {
throw DRAWAuthenticationError('userAgent cannot be null.');
}
final grant = oauth2.AuthorizationCodeGrant(_config.clientId!,
Uri.parse(_config.accessToken!), Uri.parse(_config.accessToken!),
secret: null);
_readOnly = true;
ReadOnlyAuthenticator.createUntrusted(_config, grant, deviceId)
.then(_initializationCallback)
.catchError(_initializationError);
}
Reddit._scriptInstance(
String? clientId,
String? clientSecret,
String? userAgent,
String? username,
String? password,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName) {
// Loading passed in values into config file.
_config = DRAWConfigContext(
clientId: clientId,
clientSecret: clientSecret,
userAgent: userAgent,
username: username,
password: password,
accessToken: tokenEndpoint.toString(),
authorizeUrl: authEndpoint.toString(),
configUrl: configUri.toString(),
siteName: siteName);
if (_config.clientId == null) {
throw DRAWAuthenticationError('clientId cannot be null.');
}
if (_config.clientSecret == null) {
throw DRAWAuthenticationError('clientSecret cannot be null.');
}
if (_config.userAgent == null) {
throw DRAWAuthenticationError('userAgent cannot be null.');
}
final grant = oauth2.AuthorizationCodeGrant(_config.clientId!,
Uri.parse(_config.authorizeUrl!), Uri.parse(_config.accessToken!),
secret: _config.clientSecret);
_readOnly = false;
ScriptAuthenticator.create(_config, grant)
.then(_initializationCallback)
.catchError(_initializationError);
}
Reddit._webFlowInstance(
String? clientId,
String? clientSecret,
String? userAgent,
Uri? redirectUri,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName) {
// Loading passed in values into config file.
_config = DRAWConfigContext(
clientId: clientId,
clientSecret: clientSecret,
userAgent: userAgent,
redirectUrl: redirectUri.toString(),
accessToken: tokenEndpoint.toString(),
authorizeUrl: authEndpoint.toString(),
configUrl: configUri.toString(),
siteName: siteName);
if (_config.clientId == null) {
throw DRAWAuthenticationError('clientId cannot be null.');
}
if (_config.clientSecret == null) {
throw DRAWAuthenticationError('clientSecret cannot be null.');
}
if (_config.userAgent == null) {
throw DRAWAuthenticationError('userAgent cannot be null.');
}
final grant = oauth2.AuthorizationCodeGrant(_config.clientId!,
Uri.parse(_config.authorizeUrl!), Uri.parse(_config.accessToken!),
secret: _config.clientSecret);
_initializationCallback(WebAuthenticator.create(_config, grant));
_readOnly = false;
}
Reddit._webFlowInstanceRestore(
String? clientId,
String? clientSecret,
String? userAgent,
String credentialsJson,
Uri? redirectUri,
Uri? tokenEndpoint,
Uri? authEndpoint,
Uri? configUri,
String siteName) {
// Loading passed in values into config file.
_config = DRAWConfigContext(
clientId: clientId,
clientSecret: clientSecret,
userAgent: userAgent,
redirectUrl: redirectUri.toString(),
accessToken: tokenEndpoint.toString(),
authorizeUrl: authEndpoint.toString(),
configUrl: configUri.toString(),
siteName: siteName);
if (_config.clientId == null) {
throw DRAWAuthenticationError('clientId cannot be null.');
}
if (_config.userAgent == null) {
throw DRAWAuthenticationError('userAgent cannot be null.');
}
_initializationCallback(WebAuthenticator.restore(_config, credentialsJson));
_readOnly = false;
}
Reddit.fromAuthenticator(Authenticator auth) {
_config = DRAWConfigContext();
_initializationCallback(auth);
}
/// Creates a lazily initialized [CommentRef].
///
/// `id` is the fullname ID of the comment without the ID prefix
/// (i.e., t1_).
///
/// `url` is the URL to the comment.
///
/// Only one of `id` and `url` can be provided.
CommentRef comment({String? id, /* Uri, String */ url}) {
if ((id != null) && (url != null)) {
throw DRAWArgumentError('One of either id or url can be provided');
} else if ((id == null) && (url == null)) {
throw DRAWArgumentError('id and url cannot both be null');
} else if (id != null) {
return CommentRef.withID(this, id);
}
return CommentRef.withPath(this, (url is Uri) ? url.toString() : url);
}
/// Creates a lazily initialized [SubmissionRef].
///
/// `id` is the fullname ID of the submission without the ID prefix
/// (i.e., t3_).
///
/// `url` is the URL to the submission.
///
/// Only one of `id` and `url` can be provided.
SubmissionRef submission({String? id, /* Uri, String */ url}) {
if ((id != null) && (url != null)) {
throw DRAWArgumentError('One of either id or url can be provided');
} else if ((id == null) && (url == null)) {
throw DRAWArgumentError('id and url cannot both be null');
} else if (id != null) {
return SubmissionRef.withID(this, id);
}
return SubmissionRef.withPath(this, (url is Uri) ? url.toString() : url);
}
RedditorRef redditor(String redditor) => RedditorRef.name(this, redditor);
SubredditRef subreddit(String subreddit) =>
SubredditRef.name(this, subreddit);
Future<dynamic> get(String api,
{Map<String, String?>? params,
bool objectify = true,
bool followRedirects = false}) async {
if (!_initialized) {
throw DRAWAuthenticationError(
'Cannot make requests using unauthenticated client.');
}
final path = Uri.https(defaultOAuthApiEndpoint, api);
final response =
await auth.get(path, params: params, followRedirects: followRedirects);
return objectify ? _objector.objectify(response) : response;
}
Future<dynamic> post(String api, Map<String, String?>? body,
{Map<String, Uint8List?>? files,
Map? params,
bool discardResponse = false,
bool objectify = true}) async {
if (!_initialized) {
throw DRAWAuthenticationError(
'Cannot make requests using unauthenticated client.');
}
final path = Uri.https(defaultOAuthApiEndpoint, api);
final response = await auth.post(path, body, files: files, params: params);
if (discardResponse) {
return null;
}
return objectify ? _objector.objectify(response) : response;
}
Future<dynamic> put(String api, {Map<String, String>? body}) async {
if (!_initialized) {
throw DRAWAuthenticationError(
'Cannot make requests using unauthenticated client.');
}
final path = Uri.https(defaultOAuthApiEndpoint, api);
final response = await auth.put(path, body: body);
return _objector.objectify(response);
}
Future<dynamic> delete(String api, {Map<String, String>? body}) async {
if (!_initialized) {
throw DRAWAuthenticationError(
'Cannot make requests using unauthenticated client.');
}
final path = Uri.https(defaultOAuthApiEndpoint, api);
final response = await auth.delete(path, body: body);
return _objector.objectify(response);
}
void _initializationCallback(Authenticator auth) {
_auth = auth;
_front = FrontPage(this);
_inbox = Inbox(this);
_objector = Objector(this);
_subreddits = Subreddits(this);
_user = User(this);
_initialized = true;
_initializedCompleter.complete(true);
}
void _initializationError(e) {
_initialized = false;
_initializedCompleter.completeError(e);
}
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/auth.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:oauth2/oauth2.dart' as oauth2;
import 'package:oauth2/src/handle_access_token_response.dart';
import 'package:draw/src/draw_config_context.dart';
import 'package:draw/src/exception_objector.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/logging.dart';
const String _kDeleteRequest = 'DELETE';
const String _kGetRequest = 'GET';
const String _kPostRequest = 'POST';
const String _kPutRequest = 'PUT';
const String _kAuthorizationKey = 'Authorization';
const String _kDurationKey = 'duration';
const String _kErrorKey = 'error';
const String _kGrantTypeKey = 'grant_type';
const String _kMessageKey = 'message';
const String _kPasswordKey = 'password';
const String _kTokenKey = 'token';
const String _kTokenTypeHintKey = 'token_type_hint';
const String _kUserAgentKey = 'user-agent';
const String _kUsernameKey = 'username';
final Logger _logger = Logger('Authenticator');
/// The [Authenticator] class provides an interface to interact with the Reddit API
/// using OAuth2. An [Authenticator] is responsible for keeping track of OAuth2
/// credentials, refreshing and revoking access tokens, and issuing HTTPS
/// requests using OAuth2 credentials.
abstract class Authenticator {
late oauth2.AuthorizationCodeGrant _grant;
late oauth2.Client _client;
final DRAWConfigContext _config;
Authenticator(DRAWConfigContext config, oauth2.AuthorizationCodeGrant grant)
: _config = config,
_grant = grant;
Authenticator.restore(
DRAWConfigContext config, oauth2.Credentials credentials)
: _config = config,
_client = oauth2.Client(credentials,
identifier: config.clientId,
secret: config.clientSecret,
httpClient: http.Client());
/// Not implemented for [Authenticator]s other than [WebAuthenticator].
Future<void> authorize(String code) async {
throw DRAWInternalError(
"'authorize' is only implemented for 'WebAuthenticator'");
}
/// Not implemented for [Authenticator]s other than [WebAuthenticator].
Uri url(List<String> scopes, String state,
{String duration = 'permanent', bool compactLogin = false}) {
throw DRAWInternalError("'url' is only implemented for 'WebAuthenticator'");
}
/// Request a new access token from the Reddit API. Throws a
/// [DRAWAuthenticationError] if the [Authenticator] is not yet initialized.
Future<void> refresh() async {
await _authenticationFlow();
}
/// Revokes any outstanding tokens associated with the [Authenticator].
Future<void> revoke() async {
final tokens = <Map>[];
final accessToken = {
_kTokenKey: credentials.accessToken,
_kTokenTypeHintKey: 'access_token',
};
tokens.add(accessToken);
if (credentials.refreshToken != null) {
final refreshToken = {
_kTokenKey: credentials.refreshToken,
_kTokenTypeHintKey: 'refresh_token',
};
tokens.add(refreshToken);
}
for (final token in tokens) {
final Map<String, String?> revokeAccess = <String, String>{};
revokeAccess[_kTokenKey] = token[_kTokenKey];
revokeAccess[_kTokenTypeHintKey] = token[_kTokenTypeHintKey];
var path = Uri.parse(_config.revokeToken!);
// Retrieve the client ID and secret.
final clientId = _config.clientId;
final clientSecret = _config.clientSecret;
if ((clientId != null) && (clientSecret != null)) {
final userInfo = '$clientId:$clientSecret';
path = path.replace(userInfo: userInfo);
}
final Map<String, String?> headers = <String, String>{};
headers[_kUserAgentKey] = _config.userAgent;
final httpClient = http.Client();
// Request the token from the server.
final response = await httpClient.post(path,
headers: headers as Map<String, String>?, body: revokeAccess);
if (response.statusCode != 204) {
// We should always get a 204 response for this call.
final parsed = json.decode(response.body);
_throwAuthenticationError(parsed);
}
}
}
/// Initiates the authorization flow. This method should populate a
/// [Map<String,String>] with information needed for authentication, and then
/// call [_requestToken] to authenticate. All classes inheriting from
/// [Authenticator] must implement this method.
Future<void> _authenticationFlow();
/// Make a simple `GET` request.
///
/// [path] is the destination URI that the request will be made to.
Future<dynamic> get(Uri path,
{Map<String, String?>? params, bool followRedirects = false}) async {
_logger.info('GET: $path params: ${DRAWLoggingUtils.jsonify(params)}');
return _request(_kGetRequest, path,
params: params, followRedirects: followRedirects);
}
/// Make a simple `POST` request.
///
/// [path] is the destination URI and [body] contains the POST parameters
/// that will be sent with the request.
Future<dynamic> post(Uri path, Map<String, String?>? body,
{Map<String, Uint8List?>? files, Map? params}) async {
_logger.info('POST: $path body: ${DRAWLoggingUtils.jsonify(body)}');
return _request(_kPostRequest, path,
body: body, files: files, params: params as Map<String, String?>?);
}
/// Make a simple `PUT` request.
///
/// [path] is the destination URI and [body] contains the PUT parameters that
/// will be sent with the request.
Future<dynamic> put(Uri path, {Map<String, String>? body}) async {
_logger.info('PUT: $path body: ${DRAWLoggingUtils.jsonify(body)}');
return _request(_kPutRequest, path, body: body);
}
/// Make a simple `DELETE` request.
///
/// [path] is the destination URI and [body] contains the DELETE parameters
/// that will be sent with the request.
Future<dynamic> delete(Uri path, {Map<String, String>? body}) async {
_logger.info('DELETE: $path body: ${DRAWLoggingUtils.jsonify(body)}');
return _request(_kDeleteRequest, path, body: body);
}
/// Request data from Reddit using our OAuth2 client.
///
/// [type] can be one of `GET`, `POST`, and `PUT`. [path] represents the
/// request parameters. [body] is an optional parameter which contains the
/// body fields for a POST request.
Future<dynamic> _request(String type, Uri path,
{Map<String, String?>? body,
Map<String, String?>? params,
Map<String, Uint8List?>? files,
bool followRedirects = false}) async {
if (!isValid) {
await refresh();
}
final finalPath = path.replace(queryParameters: params);
final request = http.MultipartRequest(type, finalPath);
// Some API requests initiate a redirect (i.e., random submission from a
// subreddit) but the redirect doesn't forward the OAuth credentials
// automatically. We disable redirects here and throw a DRAWRedirectResponse
// so that we can handle the redirect manually on a case-by-case basis.
request.followRedirects = followRedirects;
if (body != null) {
request.fields.addAll(Map<String, String>.from(body));
}
if (files != null) {
request.files.addAll([
for (final key in files.keys)
http.MultipartFile.fromBytes(key, files[key]!, filename: 'filename')
]);
}
http.StreamedResponse responseStream;
try {
responseStream = await _client.send(request);
} on oauth2.AuthorizationException catch (e) {
throw DRAWAuthenticationError('$e');
}
if (responseStream.isRedirect) {
var redirectStr = Uri.parse(responseStream.headers['location']!).path;
if (redirectStr.endsWith('.json')) {
redirectStr = redirectStr.substring(0, redirectStr.length - 5);
}
throw DRAWRedirectResponse(redirectStr, responseStream);
}
final response = await responseStream.stream.bytesToString();
if (response.isEmpty) return null;
final parsed = json.decode(response);
if ((parsed is Map) && responseStream.statusCode >= 400) {
parseAndThrowError(
responseStream.statusCode, parsed as Map<String, dynamic>);
}
if ((parsed is Map) && parsed.containsKey(_kErrorKey)) {
_throwAuthenticationError(parsed);
}
_logger.finest('RESPONSE: ${DRAWLoggingUtils.jsonify(parsed)}');
return parsed;
}
/// Requests the authentication token from Reddit based on parameters provided
/// in [accountInfo] and [_grant].
Future<void> _requestToken(Map<String, String?> accountInfo) async {
// Retrieve the client ID and secret.
final clientId = _grant.identifier;
final clientSecret = _grant.secret;
final userInfo = '$clientId:$clientSecret';
final httpClient = http.Client();
final start = DateTime.now();
final headers = <String, String>{};
headers[_kUserAgentKey] = _config.userAgent!;
// Request the token from the server.
final response = await httpClient.post(
_grant.tokenEndpoint.replace(userInfo: userInfo),
headers: headers,
body: accountInfo);
// Check for error response.
final responseMap = json.decode(response.body);
if (responseMap.containsKey(_kErrorKey)) {
_throwAuthenticationError(responseMap);
}
// Create the Credentials object from the authentication token.
final credentials = handleAccessTokenResponse(
response, _grant.tokenEndpoint, start, ['*'], ',');
// Generate the OAuth2 client that will be used to query Reddit servers.
_client = oauth2.Client(credentials,
identifier: clientId, secret: clientSecret, httpClient: httpClient);
}
void _throwAuthenticationError(Map response) {
final statusCode = response[_kErrorKey];
final reason = response[_kMessageKey];
throw DRAWAuthenticationError('Status Code: $statusCode Reason: $reason');
}
Future<void> _requestTokenUntrusted(Map<String, String?> accountInfo) async {
// Retrieve the client ID and secret.
final clientId = _grant.identifier;
final httpClient = http.Client();
final start = DateTime.now();
final headers = <String, String>{
_kAuthorizationKey: 'Basic ${base64Encode((clientId + ":").codeUnits)})',
if (_config.userAgent != null) _kUserAgentKey: _config.userAgent!
};
// Request the token from the server.
final response = await httpClient.post(
_grant.tokenEndpoint,
headers: headers,
body: accountInfo,
);
// Check for error response.
final responseMap = json.decode(response.body);
if (responseMap.containsKey(_kErrorKey)) {
_throwAuthenticationError(responseMap);
}
// Create the Credentials object from the authentication token.
final credentials = handleAccessTokenResponse(
response, _grant.tokenEndpoint, start, ['*'], ',');
// Generate the OAuth2 client that will be used to query Reddit servers.
_client = oauth2.Client(credentials,
identifier: clientId, httpClient: httpClient);
}
/// The credentials associated with this authenticator instance.
///
/// Returns an [oauth2.Credentials] object associated with the current
/// authenticator instance, otherwise returns [null].
oauth2.Credentials get credentials => _client.credentials;
/// The user agent value to be presented to Reddit.
///
/// Returns the user agent value which is used as an identifier for this
/// session. Provided on authenticator creation.
String get userAgent => _config.userAgent!;
/// A flag representing whether or not this authenticator instance is valid.
///
/// Returns `false` if the authentication flow has not yet been completed, if
/// [revoke] has been called, or the access token has expired.
bool get isValid {
return !(credentials.isExpired);
}
}
/// The [ScriptAuthenticator] class allows for the creation of an [Authenticator]
/// instance which is associated with a valid Reddit user account. This is to be
/// used with the 'Script' app type credentials. Refer to Reddit's
/// [documentation](https://github.com/reddit/reddit/wiki/OAuth2-App-Types)
/// for descriptions of valid app types.
class ScriptAuthenticator extends Authenticator {
ScriptAuthenticator._(
DRAWConfigContext config, oauth2.AuthorizationCodeGrant grant)
: super(config, grant);
static Future<ScriptAuthenticator> create(
DRAWConfigContext config, oauth2.AuthorizationCodeGrant grant) async {
final authenticator = ScriptAuthenticator._(config, grant);
await authenticator._authenticationFlow();
return authenticator;
}
/// Initiates the authorization flow. This method should populate a
/// [Map<String,String>] with information needed for authentication, and then
/// call [_requestToken] to authenticate.
@override
Future<void> _authenticationFlow() async {
final accountInfo = <String, String?>{};
accountInfo[_kUsernameKey] = _config.username;
accountInfo[_kPasswordKey] = _config.password;
accountInfo[_kGrantTypeKey] = 'password';
accountInfo[_kDurationKey] = 'permanent';
await _requestToken(accountInfo);
}
}
/// The [ReadOnlyAuthenticator] class allows for the creation of an [Authenticator]
/// instance which is not associated with any reddit account. As the name
/// implies, the [ReadOnlyAuthenticator] can only be used to make read-only
/// requests to the Reddit API that do not require access to a valid Reddit user
/// account. Refer to Reddit's
/// [documentation](https://github.com/reddit/reddit/wiki/OAuth2-App-Types) for
/// descriptions of valid app types.
class ReadOnlyAuthenticator extends Authenticator {
static const String _kDeviceIdKey = 'device_id';
final bool _applicationOnlyOAuth;
final String? _deviceId;
ReadOnlyAuthenticator._(
DRAWConfigContext config,
oauth2.AuthorizationCodeGrant grant,
this._applicationOnlyOAuth,
this._deviceId)
: super(config, grant);
static Future<ReadOnlyAuthenticator> create(
DRAWConfigContext config, oauth2.AuthorizationCodeGrant grant) async {
final authenticator = ReadOnlyAuthenticator._(config, grant, false, '');
await authenticator._authenticationFlow();
return authenticator;
}
static Future<ReadOnlyAuthenticator> createUntrusted(DRAWConfigContext config,
oauth2.AuthorizationCodeGrant grant, String? deviceId) async {
final authenticator =
ReadOnlyAuthenticator._(config, grant, true, deviceId);
await authenticator._authenticationFlow();
return authenticator;
}
/// Initiates the authorization flow. This method should populate a
/// [Map<String,String>] with information needed for authentication, and then
/// call [_requestToken] to authenticate.
@override
Future<void> _authenticationFlow() async {
final Map<String, String?> accountInfo = <String, String>{};
if (_applicationOnlyOAuth) {
accountInfo[_kGrantTypeKey] =
'https://oauth.reddit.com/grants/installed_client';
accountInfo[_kDeviceIdKey] = _deviceId;
await _requestTokenUntrusted(accountInfo);
} else {
accountInfo[_kGrantTypeKey] = 'client_credentials';
await _requestToken(accountInfo);
}
}
}
/// The [WebAuthenticator] class allows for the creation of an [Authenticator]
/// that exposes functionality which allows for the user to authenticate through
/// a browser. The [url] method is used to generate the URL that the user uses
/// to authenticate on www.reddit.com, and the [authorize] method retrieves the
/// access token given the returned `code`. This is to be
/// used with the 'Web' app type credentials. Refer to Reddit's
/// [documentation](https://github.com/reddit/reddit/wiki/OAuth2-App-Types)
/// for descriptions of valid app types.
class WebAuthenticator extends Authenticator {
final Uri _redirect;
WebAuthenticator._(
DRAWConfigContext config, oauth2.AuthorizationCodeGrant grant)
: _redirect = Uri.parse(config.redirectUrl!),
super(config, grant);
WebAuthenticator._restore(DRAWConfigContext config, String credentialsJson)
: _redirect = Uri.parse(config.redirectUrl!),
super.restore(config, oauth2.Credentials.fromJson(credentialsJson));
static WebAuthenticator create(
DRAWConfigContext config, oauth2.AuthorizationCodeGrant grant) =>
WebAuthenticator._(config, grant);
static WebAuthenticator restore(
DRAWConfigContext config, String credentialsJson) =>
WebAuthenticator._restore(config, credentialsJson);
/// Generates the authentication URL used for Reddit user verification in a
/// browser.
///
/// [scopes] is the list of all scopes that can be requested (see
/// https://www.reddit.com/api/v1/scopes for a list of valid scopes). [state]
/// should be a unique [String] for the current [Authenticator] instance.
/// The value of [state] will be returned via the redirect Uri and should be
/// verified against the original value of [state] to ensure the app access
/// response corresponds to the correct request. [duration] indicates whether
/// or not a permanent token is needed for the client, and can take the value
/// of either 'permanent' (default) or 'temporary'. If [compactLogin] is true,
/// then the Uri will link to a mobile-friendly Reddit authentication screen.
@override
Uri url(List<String> scopes, String state,
{String duration = 'permanent', bool compactLogin = false}) {
// TODO(bkonyi) do we want to add the [implicit] flag to the argument list?
var redditAuthUri =
_grant.getAuthorizationUrl(_redirect, scopes: scopes, state: state);
// getAuthorizationUrl returns a Uri which is missing the duration field, so
// we need to add it here.
final queryParameters =
Map<String, dynamic>.from(redditAuthUri.queryParameters);
queryParameters[_kDurationKey] = duration;
redditAuthUri = redditAuthUri.replace(queryParameters: queryParameters);
if (compactLogin) {
var path = redditAuthUri.path;
path = path.substring(0, path.length) + r'.compact';
redditAuthUri = redditAuthUri.replace(path: path);
}
return redditAuthUri;
}
/// Authorizes the current [Authenticator] instance using the code returned
/// from Reddit after the user has authenticated.
///
/// [code] is the value passed as a query parameter to `redirect`. This value
/// must be parsed from the request made to `redirect` before being passed to
/// this method.
@override
Future<void> authorize(String code) async {
_client = await _grant.handleAuthorizationCode(code);
}
/// Initiates the authorization flow. This method should populate a
/// [Map<String,String>] with information needed for authentication, and then
/// call [_requestToken] to authenticate.
@override
Future<void> _authenticationFlow() async {
throw UnimplementedError(
'_authenticationFlow is not used in WebAuthenticator.');
}
/// Request a new access token from the Reddit API. Throws a
/// [DRAWAuthenticationError] if the [Authenticator] is not yet initialized.
@override
Future<void> refresh() async {
_client = await _client.refreshCredentials();
}
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/draw_config_context.dart | /// Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
// ignore: import_of_legacy_library_into_null_safe
import 'package:ini/ini.dart';
import 'config_file_reader.dart';
import 'exceptions.dart';
import 'platform_utils.dart';
const String kAccessToken = 'access_token';
const String kAuthorize = 'authorize_uri';
const String kCheckForUpdates = 'check_for_updates';
const String kClientId = 'client_id';
const String kClientSecret = 'client_secret';
const String kComment = 'comment_kind';
const String kDefaultAccessToken =
r'https://www.reddit.com/api/v1/access_token';
const String kDefaultAuthorizeUrl = r'https://www.reddit.com/api/v1/authorize';
const String kDefaultOAuthUrl = r'oauth.reddit.com';
const String kDefaultRedditUrl = 'https://www.reddit.com';
const String kDefaultRevokeToken =
r'https://www.reddit.com/api/v1/revoke_token';
const String kDefaultShortUrl = 'https://redd.it/';
const String kHttpProxy = 'http_proxy';
const String kHttpsProxy = 'https_proxy';
const String kKind = 'kind';
const String kMessage = 'message_kind';
const String kOauthUrl = 'oauth_url';
const String kOptionalField = 'optional_field';
const String kOptionalWithDefaultValues = 'optional_with_default';
const String kPassword = 'password';
const String kRedditUrl = 'reddit_url';
const String kRedditor = 'redditor_kind';
const String kRedirectUrl = 'redirect_uri';
const String kRefreshToken = 'refresh_token';
const String kRequiredField = 'required_field';
const String kRevokeToken = 'revoke_token';
const String kShortUrl = 'short_url';
const String kSubmission = 'submission_kind';
const String kSubreddit = 'subreddit_kind';
const String kUserAgent = 'user_agent';
const String kUsername = 'username';
final Null kNotSet = null;
/// The [DRAWConfigContext] class provides an interface to store.
/// Load the DRAW's configuration file draw.ini.
class DRAWConfigContext {
/// The default Object Mapping key for [Comment].
static const String kCommentKind = 't1';
/// The default Object Mapping key for [Message].
static const String kMessageKind = 't4';
/// The default Object Mapping key for [Redditor].
static const String kRedditorKind = 't2';
/// The default Object Mapping key for [Submission].
static const String kSubmissionKind = 't3';
/// The default Object Mapping key for [Subreddit].
static const String kSubredditKind = 't5';
/// The default Object Mapping key for [Trophy].
static const String kTrophyKind = 't6';
static const Map<String, List<String>> fieldMap = {
kShortUrl: [kShortUrl],
kCheckForUpdates: [kCheckForUpdates],
kKind: [kComment, kMessage, kRedditor, kSubmission, kSubreddit],
kOptionalField: [
kClientId,
kClientSecret,
kHttpProxy,
kHttpsProxy,
kRedirectUrl,
kRefreshToken,
kPassword,
kUserAgent,
kUsername,
],
kOptionalWithDefaultValues: [
kAuthorize,
kAccessToken,
kRevokeToken,
],
kRequiredField: [kOauthUrl, kRedditUrl]
};
Config? _customConfig;
final Map<String, String> _kind = <String, String>{};
bool? _checkForUpdates;
bool get checkForUpdates => _checkForUpdates ?? false;
String? _accessToken;
String? _authorizeUrl;
String? _clientId;
String? _clientSecret;
String? _configUrl;
String? _httpProxy;
String? _httpsProxy;
String? _oauthUrl;
String? _password;
late String _primarySiteName;
String? _redditUrl;
String? _redirectUrl;
String? _refreshToken;
String? _revokeToken;
String? _shortURL;
String? _userAgent;
String? _username;
String? get accessToken => _accessToken;
String? get authorizeUrl => _authorizeUrl;
String? get clientId => _clientId;
String? get clientSecret => _clientSecret;
String get commentKind => _kind[kComment] ?? kCommentKind;
String? get configUrl => _configUrl;
String? get httpProxy => _httpProxy;
String? get httpsProxy => _httpsProxy;
String get messageKind => _kind[kMessage] ?? kMessageKind;
String? get oauthUrl => _oauthUrl;
String? get password => _password;
String? get redditUrl => _redditUrl;
String get redditorKind => _kind[kRedditor] ?? kRedditorKind;
String? get redirectUrl => _redirectUrl;
String? get refreshToken => _refreshToken;
String? get revokeToken => _revokeToken;
String get submissionKind => _kind[kSubmission] ?? kSubmissionKind;
String get subredditKind => _kind[kSubreddit] ?? kSubredditKind;
String? get userAgent => _userAgent;
String? get username => _username;
//Note this accessor throws if _shortURL is not set.
String? get shortUrl {
if (_shortURL == kNotSet) {
throw DRAWClientError('No short domain specified');
}
return _shortURL;
}
/// Creates a new [DRAWConfigContext] instance.
///
/// [siteName] is the site name associated with the section of the ini file
/// that would like to be used to load additional configuration information.
/// The default behaviour is to map to the section [default].
///
/// [_userAgent] is an arbitrary identifier used by the Reddit API to differentiate
/// between client instances. Should be unique for example related to [siteName].
///
DRAWConfigContext({
String? clientId,
String? clientSecret,
String? userAgent,
String? username,
String? password,
String? redirectUrl,
String? accessToken,
String? authorizeUrl,
String? configUrl,
String siteName = 'default',
var checkForUpdates,
}) {
// Give passed in values highest precedence for assignment.
// TODO(ckartik): Find a more robust way of giving passed in values higher priority.
// Look in to the possiblity of storing these values in a map and checking against
// it in the fetchOrNotSet function.
_primarySiteName = siteName;
_clientId = clientId;
_clientSecret = clientSecret;
_configUrl = configUrl;
_username = username;
_password = password;
_redirectUrl = redirectUrl;
_accessToken = accessToken;
_authorizeUrl = authorizeUrl;
_userAgent = userAgent;
_checkForUpdates =
checkForUpdates == null ? null : _configBool(checkForUpdates);
// TODO(bkonyi): Issue #55 - support draw.ini configs on Fuchsia.
if (!Platform.isFuchsia) {
final configFileReader = ConfigFileReader(_configUrl);
// Load the first file found in order of path preference.
final dynamic primaryFile = configFileReader.loadCorrectFile();
if (primaryFile != null) {
try {
_customConfig = Config.fromStrings(primaryFile.readAsLinesSync());
} catch (exception) {
throw DRAWClientError('Could not parse configuration file.');
}
}
}
// Create an empty config if we can't find the config or we're on Fuchsia.
_customConfig ??= Config();
// Load values found in the ini file, into the object fields.
fieldMap.forEach((key, value) => _fieldInitializer(key, value));
}
/// Take in the [type] which reflects the key in the [fieldMap]
/// [params] is the list of values found in [kFileName] file.
void _fieldInitializer(type, params) {
params.forEach((value) => _initializeField(type, value));
}
/// Initialize the attributes of the configuration object using the ini file.
void _initializeField(String type, String param) {
if (type == kShortUrl) {
_shortURL = _fetchDefault('short_url') ?? kDefaultShortUrl;
} else if (type == kCheckForUpdates) {
_checkForUpdates ??= _configBool(_fetchOrNotSet('check_for_updates'));
} else if (type == kKind) {
final value = _fetchOrNotSet(param);
if (value != null) {
_kind[param] = value;
}
} else if (type == kOptionalField) {
final value = _fetchOrNotSet(param);
if (value != null) {
switch (param) {
case kClientId:
_clientId = value;
break;
case kClientSecret:
_clientSecret = value;
break;
case kHttpProxy:
_httpProxy = value;
break;
case kHttpsProxy:
_httpsProxy = value;
break;
case kRedirectUrl:
_redirectUrl = value;
break;
case kRefreshToken:
_refreshToken = value;
break;
case kPassword:
_password = value;
break;
case kUserAgent:
//Null aware operator is here to give precedence to passed in values.
_userAgent ??= value;
break;
case kUsername:
_username = value;
break;
default:
throw DRAWInternalError(
'Parameter $param does not exist in the fieldMap for $type');
}
}
} else if (type == kOptionalWithDefaultValues) {
final value = _fetchOrNotSet(param);
switch (param) {
case kAccessToken:
_accessToken = value ?? kDefaultAccessToken;
break;
case kAuthorize:
_authorizeUrl = value ?? kDefaultAuthorizeUrl;
break;
case kRevokeToken:
_revokeToken = value ?? kDefaultRevokeToken;
break;
default:
throw DRAWInternalError(
'Parameter $param does not exist in the fieldMap for $type');
}
} else if (type == kRequiredField) {
final value = _fetchOrNotSet(param);
switch (param) {
case kOauthUrl:
_oauthUrl = value ?? kDefaultOAuthUrl;
break;
case kRedditUrl:
_redditUrl = value ?? kDefaultRedditUrl;
break;
default:
throw DRAWInternalError(
'Parameter $param does not exist in the fieldMap for $type');
}
}
}
/// Safely return the truth value associated with [item].
bool _configBool(final item) {
if (item is bool) {
return item;
} else if (item is String) {
final trueValues = ['1', 'yes', 'true', 'on'];
return trueValues.contains(item.toLowerCase());
} else {
return false;
}
}
/// Fetch the value under the default site section in the ini file.
String? _fetchDefault(String key) {
return _customConfig!.get('default', key);
}
String? _fetchOptional(String key) {
try {
return _customConfig!.get(_primarySiteName, key);
} catch (exception) {
throw DRAWArgumentError(
'Invalid paramter value, siteName cannot be null');
}
}
/// Checks if [key] is contained in the parsed ini file, if not returns [kNotSet].
///
/// [key] is the key to be searched in the draw.ini file.
String? _fetchOrNotSet(final key) =>
(_fetchOptional(key) ?? _fetchDefault(key) ?? kNotSet);
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/image_file_reader_unsupported.dart | /// Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
Future<Map> loadImage(Uri? imagePath) async =>
throw UnsupportedError('Loading images from disk is not supported on web.');
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/base.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
export 'base_impl.dart' hide setData;
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/api_paths.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
/// A [Map] containing all of the Reddit API paths.
final Map apiPath = {
'about_edited': 'r/{subreddit}/about/edited/',
'about_log': 'r/{subreddit}/about/log/',
'about_modqueue': 'r/{subreddit}/about/modqueue/',
'about_reports': 'r/{subreddit}/about/reports/',
'about_spam': 'r/{subreddit}/about/spam/',
'about_sticky': 'r/{subreddit}/about/sticky/',
'about_stylesheet': 'r/{subreddit}/about/stylesheet/',
'about_traffic': 'r/{subreddit}/about/traffic/',
'about_unmoderated': 'r/{subreddit}/about/unmoderated/',
'accept_mod_invite': 'r/{subreddit}/api/accept_moderator_invite',
'approve': 'api/approve/',
'block': 'api/block',
'blocked': 'prefs/blocked/',
'collapse': 'api/collapse_message/',
'comment': 'api/comment/',
'comment_replies': 'message/comments/',
'compose': 'api/compose/',
'contest_mode': 'api/set_contest_mode/',
'del': 'api/del/',
'del_msg': 'api/del_msg',
'deleteflair': 'r/{subreddit}/api/deleteflair',
'delete_sr_banner': 'r/{subreddit}/api/delete_sr_banner',
'delete_sr_header': 'r/{subreddit}/api/delete_sr_header',
'delete_sr_icon': 'r/{subreddit}/api/delete_sr_icon',
'delete_sr_image': 'r/{subreddit}/api/delete_sr_img',
'distinguish': 'api/distinguish/',
'domain': 'domain/{domain}/',
'downvoted': '/user/{user}/downvoted',
'duplicates': 'duplicates/{submission_id}/',
'edit': 'api/editusertext/',
'flair': 'r/{subreddit}/api/flair/',
'flairconfig': 'r/{subreddit}/api/flairconfig/',
'flaircsv': 'r/{subreddit}/api/flaircsv/',
'flairlist': 'r/{subreddit}/api/flairlist/',
'flairselector': 'r/{subreddit}/api/flairselector/',
'flairtemplate': 'r/{subreddit}/api/flairtemplate/',
'flairtemplateclear': 'r/{subreddit}/api/clearflairtemplates/',
'flairtemplatedelete': 'r/{subreddit}/api/deleteflairtemplate/',
'friend': 'r/{subreddit}/api/friend/',
'friend_v1': 'api/v1/me/friends/{user}',
'friends': 'api/v1/me/friends/',
'gild_thing': 'api/v1/gold/gild/{fullname}/',
'gild_user': 'api/v1/gold/give/{username}/',
'hide': 'api/hide/',
'ignore_reports': 'api/ignore_reports/',
'inbox': 'message/inbox/',
'info': 'api/info/',
'karma': 'api/v1/me/karma',
'leavecontributor': 'api/leavecontributor',
'leavemoderator': 'api/leavemoderator',
'link_flair': 'r/{subreddit}/api/link_flair',
'list_banned': 'r/{subreddit}/about/banned/',
'list_contributor': 'r/{subreddit}/about/contributors/',
'list_moderator': 'r/{subreddit}/about/moderators/',
'list_muted': 'r/{subreddit}/about/muted/',
'list_wikibanned': 'r/{subreddit}/about/wikibanned/',
'list_wikicontributor': 'r/{subreddit}/about/wikicontributors/',
'live_accept_invite': 'api/live/{id}/accept_contributor_invite',
'live_add_update': 'api/live/{id}/update',
'live_close': 'api/live/{id}/close_thread',
'live_contributors': 'live/{id}/contributors',
'live_discussions': 'live/{id}/discussions',
'live_info': 'api/live/by_id/{ids}',
'live_invite': 'api/live/{id}/invite_contributor',
'live_leave': 'api/live/{id}/leave_contributor',
'live_now': 'api/live/happening_now',
'live_remove_update': 'api/live/{id}/delete_update',
'live_remove_contrib': 'api/live/{id}/rm_contributor',
'live_remove_invite': 'api/live/{id}/rm_contributor_invite',
'live_report': 'api/live/{id}/report',
'live_strike': 'api/live/{id}/strike_update',
'live_update_perms': 'api/live/{id}/set_contributor_permissions',
'live_update_thread': 'api/live/{id}/edit',
'live_updates': 'live/{id}',
'liveabout': 'api/live/{id}/about/',
'livecreate': 'api/live/create',
'lock': 'api/lock/',
'me': 'api/v1/me',
'mentions': 'message/mentions',
'message': 'message/messages/{id}/',
'messages': 'message/messages/',
'moderator_messages': 'r/{subreddit}/message/moderator/',
'moderator_unread': 'r/{subreddit}/message/moderator/unread/',
'morechildren': 'api/morechildren/',
'my_contributor': 'subreddits/mine/contributor/',
'my_moderator': 'subreddits/mine/moderator/',
'my_multireddits': 'api/multi/mine/',
'my_subreddits': 'subreddits/mine/subscriber/',
'marknsfw': 'api/marknsfw/',
'modmail_archive': 'api/mod/conversations/{id}/archive',
'modmail_bulk_read': 'api/mod/conversations/bulk/read',
'modmail_conversation': 'api/mod/conversations/{id}',
'modmail_conversations': 'api/mod/conversations/',
'modmail_highlight': 'api/mod/conversations/{id}/highlight',
'modmail_mute': 'api/mod/conversations/{id}/mute',
'modmail_read': 'api/mod/conversations/read',
'modmail_subreddits': 'api/mod/conversations/subreddits',
'modmail_unarchive': 'api/mod/conversations/{id}/unarchive',
'modmail_unmute': 'api/mod/conversations/{id}/unmute',
'modmail_unread': 'api/mod/conversations/unread',
'modmail_unread_count': 'api/mod/conversations/unread/count',
'multireddit': 'user/{user}/m/{multi}/',
'multireddit_api': 'api/multi/user/{user}/m/{multi}/',
'multireddit_base': 'api/multi/',
'multireddit_copy': 'api/multi/copy/',
'multireddit_rename': 'api/multi/rename/',
'multireddit_update': 'api/multi/user/{user}/m/{multi}/r/{subreddit}',
'multireddit_user': 'api/multi/user/{user}/',
'mute_sender': 'api/mute_message_author/',
'quarantine_opt_in': 'api/quarantine_optin',
'quarantine_opt_out': 'api/quarantine_optout',
'read_message': 'api/read_message/',
'remove': 'api/remove/',
'report': 'api/report/',
'rules': 'r/{subreddit}/about/rules',
'save': 'api/save/',
'search': 'r/{subreddit}/search/',
'select_flair': 'r/{subreddit}/api/selectflair/',
'sendreplies': 'api/sendreplies/',
'sent': 'message/sent/',
'setpermissions': 'r/{subreddit}/api/setpermissions/',
'spoiler': 'api/spoiler/',
'site_admin': 'api/site_admin/',
'sticky_submission': 'api/set_subreddit_sticky/',
'sub_recommended': 'api/recommend/sr/{subreddits}',
'submission': 'comments/{id}/',
'submission_replies': 'message/selfreply/',
'submit': 'api/submit/',
'subreddit': 'r/{subreddit}/',
'subreddit_about': 'r/{subreddit}/about/',
'subreddit_filter': ('api/filter/user/{user}/f/{special}/'
'r/{subreddit}'),
'subreddit_filter_list': 'api/filter/user/{user}/f/{special}',
'subreddit_random': 'r/{subreddit}/random/',
'subreddit_settings': 'r/{subreddit}/about/edit/',
'subreddit_stylesheet': 'r/{subreddit}/api/subreddit_stylesheet/',
'subreddits_default': 'subreddits/default/',
'subreddits_gold': 'subreddits/premium/',
'subreddits_new': 'subreddits/new/',
'subreddits_popular': 'subreddits/popular/',
'subreddits_name_search': 'api/search_reddit_names/',
'subreddits_search': 'subreddits/search/',
'subscribe': 'api/subscribe/',
'suggested_sort': 'api/set_suggested_sort/',
'trophies': 'api/v1/user/{username}/trophies',
'uncollapse': 'api/uncollapse_message',
'unfriend': 'r/{subreddit}/api/unfriend/',
'unhide': 'api/unhide/',
'unignore_reports': 'api/unignore_reports/',
'unlock': 'api/unlock/',
'unmarknsfw': 'api/unmarknsfw/',
'unmute_sender': 'api/unmute_message_author/',
'unread': 'message/unread/',
'unread_message': 'api/unread_message/',
'unsave': 'api/unsave/',
'unspoiler': 'api/unspoiler/',
'upload_image': 'r/{subreddit}/api/upload_sr_img',
'upvoted': 'user/{user}/upvoted',
'user': 'user/{user}/',
'user_about': 'user/{user}/about/',
'vote': 'api/vote/',
'wiki_edit': 'r/{subreddit}/api/wiki/edit/',
'wiki_page': 'r/{subreddit}/wiki/{page}',
'wiki_page_editor': 'r/{subreddit}/api/wiki/alloweditor/{method}',
'wiki_page_revisions': 'r/{subreddit}/wiki/revisions/{page}',
'wiki_page_settings': 'r/{subreddit}/wiki/settings/{page}',
'wiki_pages': 'r/{subreddit}/wiki/pages/',
'wiki_revisions': 'r/{subreddit}/wiki/revisions/'
};
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/config_file_reader.dart | /// Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
export 'config_file_reader_unsupported.dart'
if (dart.library.io) 'config_file_reader_io.dart';
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/base_impl.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/reddit.dart';
void setData(RedditBaseInitializedMixin base, Map? data) {
base._data = data;
}
abstract class RedditBaseInitializedMixin {
Reddit get reddit;
String get infoPath;
Map<String, String>? get infoParams => null;
/// Returns the raw properties dictionary for this object.
///
/// This getter returns null if the object is lazily initialized.
Map? get data => _data;
Map? _data;
/// The fullname of a Reddit object.
///
/// Reddit object fullnames take the form of 't3_15bfi0'.
String? get fullname => (data == null) ? null : data!['name'];
/// The id of a Reddit object.
///
/// Reddit object ids take the form of '15bfi0'.
String? get id => (data == null) ? null : data!['id'];
/// Requests updated information from the Reddit API and updates the current
/// object properties.
Future<dynamic> refresh() async {
final response = await reddit.get(infoPath, params: infoParams);
if (response is Map) {
_data = response;
} else if (response is List) {
// TODO(bkonyi): this is for populating a Submission, since requesting
// Submission returns a list of listings, containing a Submission at [0]
// and a listing of Comments at [1]. This probably needs to be changed
// at some point to be a bit more robust, but it works for now.
_data = response[0]['listing'][0].data;
return [this, response[1]['listing']];
} else {
throw DRAWInternalError('Refresh response is of unknown type: '
'${response.runtimeType}.');
}
return this;
}
@override
String toString() {
if (_data != null) {
final encoder = JsonEncoder.withIndent(' ');
return encoder.convert(_data);
}
return 'null';
}
}
/// A base class for most DRAW objects which handles lazy-initialization of
/// objects and Reddit API request state.
abstract class RedditBase {
/// The current [Reddit] instance.
final Reddit reddit;
Map<String, String>? get infoParams => null;
/// The base request format for the current object.
String get infoPath => _infoPath;
late String _infoPath;
RedditBase(this.reddit);
RedditBase.withPath(this.reddit, String infoPath) : _infoPath = infoPath;
/// Requests the data associated with the current object.
Future<dynamic> fetch() async => reddit.get(infoPath, params: infoParams);
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/platform_utils.dart | /// Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
export 'platform_utils_unsupported.dart'
if (dart.library.io) 'platform_utils_io.dart';
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/platform_utils_io.dart | /// Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
import 'dart:io' as io;
class Platform {
static bool get isAndroid => io.Platform.isAndroid;
static bool get isFuchsia => io.Platform.isFuchsia;
static bool get isIOS => io.Platform.isIOS;
static bool get isLinux => io.Platform.isLinux;
static bool get isMacOS => io.Platform.isMacOS;
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/config_file_reader_io.dart | /// Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
import 'dart:io';
import 'package:path/path.dart' as path;
import 'exceptions.dart';
const String kLinuxEnvVar = 'XDG_CONFIG_HOME';
const String kLinuxHomeEnvVar = 'HOME';
const String kMacEnvVar = 'HOME';
const String kFileName = 'draw.ini';
const String kWindowsEnvVar = 'APPDATA';
class ConfigFileReader {
/// Path to Local, User, Global Configuration Files, with matching precedence.
late Uri _localConfigPath;
late Uri _userConfigPath;
String? _configUrl;
ConfigFileReader(String? configUrl) {
_configUrl = configUrl;
_localConfigPath = _getLocalConfigPath();
_userConfigPath = _getUserConfigPath();
}
/// Loads file from [_localConfigPath] or [_userConfigPath].
File? loadCorrectFile() {
if (_configUrl != null) {
final primaryFile = File(_configUrl!);
if (primaryFile.existsSync()) {
return primaryFile;
}
}
// Check if file exists locally.
var primaryFile = File(_localConfigPath.toFilePath());
if (primaryFile.existsSync()) {
_configUrl = _localConfigPath.toString();
return primaryFile;
}
// Check if file exists in user directory.
primaryFile = File(_userConfigPath.toFilePath());
if (primaryFile.existsSync()) {
_configUrl = _userConfigPath.toString();
return primaryFile;
}
return null;
}
/// Returns path to user level configuration file.
/// Special Behaviour: if User Config Environment var unset,
/// uses [$HOME] or the corresponding root path for the os.
Uri _getUserConfigPath() {
final environment = Platform.environment;
String? osConfigPath;
// Load correct path for user level configuration paths based on operating system.
if (Platform.isMacOS) {
osConfigPath = path.join(environment[kMacEnvVar]!, '.config');
} else if (Platform.isLinux) {
osConfigPath = environment[kLinuxEnvVar] ?? environment[kLinuxHomeEnvVar];
} else if (Platform.isWindows) {
osConfigPath = environment[kWindowsEnvVar];
} else if (Platform.isIOS) {
// TODO(ckartik): Look into supporting plists. May need to reorg workflow.
} else if (Platform.isAndroid) {
// TODO(ckartik): Look into supporting android configuration files.
} else {
throw DRAWInternalError('OS not Recognized by DRAW');
}
if (osConfigPath == null) {
// Sets osConfigPath to the corresponding root path
// based on the os.
final osDir = path.Context();
final cwd = osDir.current;
osConfigPath = osDir.rootPrefix(cwd);
}
return path.toUri(path.join(osConfigPath, kFileName));
}
/// Returns path to local configuration file.
Uri _getLocalConfigPath() {
final osDir = path.Context();
final cwd = osDir.current;
return path.toUri(path.join(cwd, kFileName));
}
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/user.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/listing/listing_generator.dart';
import 'package:draw/src/models/multireddit.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/subreddit.dart';
/// The [User] class provides methods to access information about the currently
/// authenticated user.
class User extends RedditBase {
User(Reddit reddit) : super(reddit);
/// Returns a [Future<List<Redditor>>] of blocked Redditors.
Future<List<Redditor>> blocked() async {
return (await reddit.get(apiPath['blocked'])).cast<Redditor>();
}
/// Returns a [Stream] of [Subreddit]s the currently authenticated user is a
/// contributor of.
///
/// [limit] is the number of [Subreddit]s to request, and [params] should
/// contain any additional parameters that should be sent as part of the API
/// request.
Stream<Subreddit> contributorSubreddits(
{int limit = ListingGenerator.defaultRequestLimit,
Map<String, String>? params}) =>
ListingGenerator.generator<Subreddit>(reddit, apiPath['my_contributor'],
limit: limit, params: params);
/// Returns a [Future<List<Redditor>>] of friends.
Future<List<Redditor>> friends() async {
return (await reddit.get(apiPath['friends'])).cast<Redditor>();
}
/// Returns a [Future<Map>] mapping subreddits to karma earned on the given
/// subreddit.
Future<Map<Subreddit, Map<String, int>>?> karma() async {
return (await reddit.get(apiPath['karma']))
as Map<Subreddit, Map<String, int>>?;
}
// TODO(bkonyi): actually do something with [useCache].
/// Returns a [Future<Redditor>] which represents the current user.
Future<Redditor?> me({useCache = true}) async {
return (await reddit.get(apiPath['me'])) as Redditor?;
}
/// Returns a [Stream] of [Subreddit]s the currently authenticated user is a
/// moderator of.
///
/// [limit] is the number of [Subreddit]s to request, and [params] should
/// contain any additional parameters that should be sent as part of the API
/// request.
Stream<Subreddit> moderatorSubreddits(
{int limit = ListingGenerator.defaultRequestLimit,
Map<String, String>? params}) =>
ListingGenerator.generator<Subreddit>(reddit, apiPath['my_moderator'],
limit: limit, params: params);
/// Returns a [Stream] of [Multireddit]s that belongs to the currently
/// authenticated user.
///
/// [limit] is the number of [Subreddit]s to request, and [params] should
/// contain any additional parameters that should be sent as part of the API
/// request.
Future<List<Multireddit>?> multireddits() async {
return (await reddit.get(apiPath['my_multireddits'])).cast<Multireddit>();
}
/// Returns a [Stream] of [Subreddit]s the currently authenticated user is a
/// subscriber of.
///
/// [limit] is the number of [Subreddit]s to request, and [params] should
/// contain any additional parameters that should be sent as part of the API
/// request. If provided, `after` specifies from which point
/// Reddit will return objects of the requested type.
Stream<Subreddit> subreddits(
{int limit = ListingGenerator.defaultRequestLimit,
String? after,
Map<String, String>? params}) =>
ListingGenerator.generator<Subreddit>(reddit, apiPath['my_subreddits'],
limit: limit, after: after, params: params);
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/exception_objector.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'package:draw/src/exceptions.dart';
const int kHttpBadRequest = 400;
const int kHttpNotFound = 404;
void parseAndThrowError(int status, Map<String, dynamic> response) {
switch (status) {
case kHttpBadRequest:
case kHttpNotFound:
throw DRAWNotFoundException(response['reason'], response['message']);
default:
throw DRAWUnknownResponseException(status, response.toString());
}
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/image_file_reader_io.dart | /// Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
import 'dart:io';
import 'package:draw/src/models/subreddit.dart';
import 'package:collection/collection.dart';
const String _kJpegHeader = '\xff\xd8\xff';
Future<Map> loadImage(Uri imagePath) async {
final image = File.fromUri(imagePath);
if (!await image.exists()) {
throw FileSystemException('File does not exist', imagePath.toString());
}
final imageBytes = await image.readAsBytes();
if (imageBytes.length < _kJpegHeader.length) {
throw FormatException('Invalid image format for file $imagePath.');
}
final header = imageBytes.sublist(0, _kJpegHeader.length);
final isJpeg =
const IterableEquality().equals(_kJpegHeader.codeUnits, header);
return {
'imageBytes': imageBytes,
'imageType': isJpeg ? ImageFormat.jpeg : ImageFormat.png,
};
}
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/image_file_reader.dart | /// Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
export 'image_file_reader_unsupported.dart'
if (dart.library.io) 'image_file_reader_io.dart';
| 0 |
mirrored_repositories/DRAW/lib | mirrored_repositories/DRAW/lib/src/objector.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'package:draw/src/base.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/models/comment_forest.dart';
import 'package:draw/src/models/comment_impl.dart';
import 'package:draw/src/models/flair.dart';
import 'package:draw/src/models/message.dart';
import 'package:draw/src/models/multireddit.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/submission_impl.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/models/subreddit_moderation.dart';
import 'package:draw/src/models/trophy.dart';
import 'package:draw/src/modmail.dart';
import 'package:draw/src/reddit.dart';
//final //logger = Logger('Objector');
/// Converts responses from the Reddit API into instances of [RedditBase].
class Objector extends RedditBase {
Objector(Reddit reddit) : super(reddit);
// Used in test cases to trigger a DRAWAuthenticationError
static const _testThrowKind = 'DRAW_TEST_THROW_AUTH_ERROR';
static String _removeIDPrefix(String id) {
return id.split('_')[1];
}
dynamic _objectifyDictionary(Map data) {
//logger.log(Level.INFO, '_objectifyDictionary');
// TODO(bkonyi): collapse most of the 'kind' checks.
if (data.containsKey('name')) {
// Redditor type.
//logger.log(Level.FINE, 'parsing Redditor');
return Redditor.parse(reddit, data);
} else if (data.containsKey('kind') &&
(data['kind'] == Reddit.defaultCommentKind)) {
final commentData = data['data'];
final comment = Comment.parse(reddit, commentData);
////logger.log(Level.INFO, 'parsing Comment(id: ${comment.id})');
////logger.log(Level.INFO, 'Comment Data: ${DRAWLoggingUtils.jsonify(data)}');
if (commentData.containsKey('replies') &&
(commentData['replies'] is Map) &&
commentData['replies'].containsKey('kind') &&
(commentData['replies']['kind'] == 'Listing') &&
commentData['replies'].containsKey('data') &&
(commentData['replies']['data'] is Map) &&
commentData['replies']['data'].containsKey('children')) {
//logger.log(Level.FINE, 'and parsing CommentForest for ${comment.id}');
final replies =
_objectifyList(commentData['replies']['data']['children']);
//logger.log(Level.INFO, 'Done objectifying list of comments for CommentForest for ${comment.id}');
final submission = SubmissionRef.withID(
reddit, _removeIDPrefix(commentData['link_id']));
//logger.log(Level.INFO, 'Parent submission for Comment(id: ${comment.id}): ${_removeIDPrefix(commentData["link_id"])}');
final commentForest = CommentForest(submission, replies);
setRepliesInternal(comment, commentForest);
}
return comment;
} else if (data.containsKey('kind') &&
(data['kind'] == Reddit.defaultSubmissionKind)) {
return Submission.parse(reddit, data['data']);
} else if (data.containsKey('kind') &&
(data['kind'] == Reddit.defaultSubredditKind)) {
return Subreddit.parse(reddit, data);
} else if (data.containsKey('kind') &&
data['kind'] == Reddit.defaultMessageKind) {
return Message.parse(reddit, data['data']);
} else if (data.containsKey('kind') && data['kind'] == 'stylesheet') {
final stylesheetData = data['data'];
final stylesheet = stylesheetData['stylesheet'];
final images = <StyleSheetImage>[];
if (stylesheetData.containsKey('images')) {
final rawImages = stylesheetData['images'];
for (final i in rawImages) {
images
.add(StyleSheetImage(Uri.parse(i['url']), i['link'], i['name']));
}
}
return StyleSheet(stylesheet, images);
} else if (data.containsKey('kind') && (data['kind'] == 'LabeledMulti')) {
assert(
data.containsKey('data'),
'field "data" is expected in a response'
'of type "LabeledMulti"');
return Multireddit.parse(reddit, data);
} else if (data.containsKey('kind') && (data['kind'] == 'modaction')) {
return buildModeratorAction(reddit, data['data']);
} else if (data.containsKey('sr') &&
data.containsKey('comment_karma') &&
data.containsKey('link_karma')) {
final subreddit = Subreddit.parse(reddit, data['sr']);
final value = {
'commentKarma': data['comment_karma'],
'linkKarma': data['link_karma'],
'awarderKarma': data['awarder_karma'],
'awardeeKarma': data['awardee_karma'],
};
return {subreddit: value};
} else if ((data.length == 3) &&
data.containsKey('day') &&
data.containsKey('hour') &&
data.containsKey('month')) {
return SubredditTraffic.parseTrafficResponse(data);
} else if (data.containsKey('rules')) {
final rules = <Rule>[];
for (final rawRule in data['rules']) {
rules.add(Rule.parse(rawRule));
}
return rules;
} else if (data.containsKey('kind') && (data['kind'] == _testThrowKind)) {
throw DRAWAuthenticationError('This is an error that should only be '
'seen in tests. Please file an issue if you see this while not running'
' tests.');
} else if (data.containsKey('users')) {
final flairListRaw = data['users'].cast<Map<String, dynamic>>();
final flairList = <Flair>[];
for (final flair in flairListRaw) {
flairList.add(Flair.parse(reddit, flair.cast<String, String>()));
}
return flairList;
} else if (data.containsKey('status') &&
data.containsKey('errors') &&
data.containsKey('ok') &&
data.containsKey('warnings')) {
// Flair update response.
return data;
} else if (data.containsKey('current') && data.containsKey('choices')) {
// Flair template listing.
return data;
} else if (data.containsKey('conversations')) {
// Modmail conversations.
return data;
} else if (data.containsKey('conversation')) {
// Single modmail conversation.
return ModmailConversation.parse(reddit, data as Map<String, dynamic>)
.data;
} else if (data.containsKey('body') &&
data.containsKey('author') &&
data.containsKey('isInternal')) {
return ModmailMessage.parse(reddit, data as Map<String, dynamic>?);
} else if (data.containsKey('date') && data.containsKey('actionTypeId')) {
return ModmailAction.parse(reddit, data as Map<String, dynamic>);
} else if (data.containsKey('timestamp') &&
data.containsKey('reason') &&
data.containsKey('page') &&
data.containsKey('id')) {
return data;
} else if (data['kind'] == 'TrophyList') {
return _objectifyList(data['data']['trophies']);
} else {
throw DRAWInternalError('Cannot objectify unsupported'
' response:\n$data');
}
}
List _objectifyList(List listing) {
//logger.log(Level.FINE, 'objectifying list(len: ${listing.length})');
final objectifiedListing = List<dynamic>.filled(listing.length, null);
for (var i = 0; i < listing.length; ++i) {
objectifiedListing[i] = objectify(listing[i]);
}
return objectifiedListing;
}
/// Converts a response from the Reddit API into an instance of [RedditBase]
/// or a container of [RedditBase] objects.
///
/// [data] should be one of [List] or [Map], and the return type is one of
/// [RedditBase], [List<RedditBase>], or [Map<RedditBase>] depending on the
/// response type.
dynamic objectify(dynamic data) {
//logger.log(Level.FINE, 'objectifying');
if (data == null) {
return null;
}
if (data is List) {
return _objectifyList(data);
} else if (data is! Map) {
throw DRAWInternalError('data must be of type List or Map, got '
'${data.runtimeType}');
} else if (data.containsKey('kind')) {
final kind = data['kind'];
if (kind == 'Listing') {
//logger.log(Level.FINE, 'parsing Listing');
final listing = data['data']['children'];
final before = data['data']['before'];
final after = data['data']['after'];
final objectifiedListing = _objectifyList(listing);
final result = {
'listing': objectifiedListing,
'before': before,
'after': after
};
return result;
} else if (kind == 'UserList') {
//logger.log(Level.FINE, 'parsing UserList');
final listing = data['data']['children'];
return _objectifyList(listing);
} else if (kind == 'KarmaList') {
//logger.log(Level.FINE, 'parsing KarmaList');
final listing = _objectifyList(data['data']);
final karmaMap = <Subreddit, Map<String, int>>{};
listing.forEach((map) {
karmaMap.addAll(map);
});
return karmaMap;
} else if (kind == 't2') {
// Account information about a redditor who isn't the currently
// authenticated user.
//logger.log(Level.INFO, 'account information for non-current user');
return data['data'];
} else if (kind == 'more') {
//logger.log(Level.INFO, 'parsing MoreComments');
//logger.log(Level.INFO, 'Data: ${DRAWLoggingUtils.jsonify(data["data"])}');
return MoreComments.parse(reddit, data['data']);
} else if (kind == 't6') {
return Trophy.parse(reddit, data['data']);
} else {
//logger.log(Level.INFO, 't2 but not more comments or Redditor');
return _objectifyDictionary(data);
}
} else if (data.containsKey('json')) {
if (data['json'].containsKey('data')) {
// Response from Subreddit.submit.
//logger.log(Level.FINE, 'Subreddit.submit response');
if (data['json']['data'].containsKey('url')) {
return Submission.parse(reddit, data['json']['data']);
} else if (data['json']['data'].containsKey('things')) {
return _objectifyList(data['json']['data']['things']);
} else {
throw DRAWInternalError('Invalid json response: $data');
}
} else if (data['json'].containsKey('errors')) {
const kSubredditNoExist = 'SUBREDDIT_NOEXIST';
const kUserDoesntExist = 'USER_DOESNT_EXIST';
final errors = data['json']['errors'];
//logger.log(Level.SEVERE, 'Error response: $errors');
if (errors is List && errors.isNotEmpty) {
final error = errors[0][0];
final field = errors[0].last;
switch (error) {
case kSubredditNoExist:
throw DRAWInvalidSubredditException(field);
case kUserDoesntExist:
throw DRAWInvalidRedditorException(field);
default:
// TODO(bkonyi): make an actual exception for this.
throw DRAWUnimplementedError('Error response: $errors');
}
}
return null;
} else {
throw DRAWInternalError('Invalid json response: $data');
}
}
return _objectifyDictionary(data);
}
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/flair.dart | import 'dart:convert';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/models/redditor.dart';
enum FlairPosition { left, right, disabled }
String flairPositionToString(FlairPosition p) {
switch (p) {
case FlairPosition.left:
return 'left';
case FlairPosition.right:
return 'right';
default:
throw DRAWUnimplementedError();
}
}
FlairPosition stringToFlairPosition(String? p) {
switch (p) {
case 'left':
return FlairPosition.left;
case 'right':
return FlairPosition.right;
default:
return FlairPosition.disabled;
}
}
class _FlairBase {
String? get flairCssClass => _data['flair_css_class'];
String? get flairText => _data['flair_text'];
final Map<String, dynamic> _data;
_FlairBase(String flairCssClass, String flairText)
: _data = <String, dynamic>{
'flair_css_class': flairCssClass,
'flair_text': flairText
};
_FlairBase.parse(Map<String, dynamic> data) : _data = data;
@override
String toString() => JsonEncoder.withIndent(' ').convert(_data);
}
/// A simple representation of a template for Reddit flair.
class FlairTemplate extends _FlairBase {
String get flairTemplateId => _data['flair_template_id'];
bool get flairTextEditable => _data['flair_text_editable'];
final FlairPosition position;
FlairTemplate(String flairCssClass, String flairTemplateId,
bool flairTextEditable, String flairText, this.position)
: super(flairCssClass, flairText) {
_data['flair_template_id'] = flairTemplateId;
_data['flair_text_editable'] = flairTextEditable;
}
FlairTemplate.parse(Map<String, dynamic> data)
: position = stringToFlairPosition(data['flair_position']),
super.parse(data);
}
/// A simple representation of Reddit flair.
class Flair extends _FlairBase {
final RedditorRef user;
Flair(this.user, {String flairCssClass = '', String flairText = ''})
: super(flairCssClass, flairText);
Flair.parse(Reddit reddit, Map<String, dynamic> data)
: user = RedditorRef.name(reddit, data['user']),
super.parse(data);
@override
String toString() => JsonEncoder.withIndent(' ').convert(_data);
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/redditor.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/getter_utils.dart';
import 'package:draw/src/listing/mixins/base.dart';
import 'package:draw/src/listing/mixins/gilded.dart';
import 'package:draw/src/listing/mixins/redditor.dart';
import 'package:draw/src/models/comment.dart';
import 'package:draw/src/models/mixins/messageable.dart';
import 'package:draw/src/models/multireddit.dart';
import 'package:draw/src/models/submission.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/models/trophy.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/util.dart';
/// A fully initialized class representing a particular Reddit user, also
/// known as a Redditor.
class Redditor extends RedditorRef with RedditBaseInitializedMixin {
/// The amount of comment karma earned by the Redditor.
int? get commentKarma => data!['comment_karma'];
/// The amount of awarder karma earned by the Redditor.
int? get awarderKarma => data!['awarder_karma'];
/// The amount of awardee karma earned by the Redditor.
int? get awardeeKarma => data!['awardee_karma'];
/// The time the Redditor's account was created.
DateTime? get createdUtc => GetterUtils.dateTimeOrNull(data!['created_utc']);
/// The amount of Reddit Gold creddits a Redditor currently has.
int? get goldCreddits => data!['gold_creddits'];
/// The UTC date and time that the Redditor's Reddit Gold subscription ends.
///
/// Returns `null` if the Redditor does not have Reddit Gold.
DateTime? get goldExpiration =>
GetterUtils.dateTimeOrNull(data!['gold_expiration']);
/// Redditor has Reddit Gold.
bool? get hasGold => data!['is_gold'];
/// Redditor has Mod Mail.
bool? get hasModMail => data!['has_mod_mail'];
/// Redditor has a verified email address.
bool? get hasVerifiedEmail => data!['has_verified_email'];
/// Redditor has opted into the Reddit beta.
bool? get inBeta => data!['in_beta'];
/// Number of [Message]s in the Redditor's [Inbox].
int? get inboxCount => data!['inbox_count'];
/// Redditor is a Reddit employee.
bool? get isEmployee => data!['is_employee'];
/// Redditor is a Moderator.
bool? get isModerator => data!['is_mod'];
/// The suspension status of the current Redditor.
bool? get isSuspended => data!['is_suspended'];
/// The amount of link karma earned by the Redditor.
int? get linkKarma => data!['link_karma'];
/// The list of moderator permissions for the user.
///
/// Only populated for moderator related calls for a [Subreddit].
List<ModeratorPermission> get moderatorPermissions =>
stringsToModeratorPermissions(data!['mod_permissions'].cast<String>());
/// Redditor has new Mod Mail.
bool? get newModMailExists => data!['new_modmail_exists'];
/// The note associated with a friend.
///
/// Only populated for responses from friend related called.
String? get note => data!['note'];
/// Redditor can see 18+ content.
bool? get over18 => data!['over_18'];
/// Whether the Redditor has chosen to filter profanity.
bool? get preferNoProfanity => data!['pref_no_profanity'];
/// The date and time when the Redditor's suspension ends.
DateTime? get suspensionExpirationUtc =>
GetterUtils.dateTimeOrNull(data!['suspension_expiration_utc']);
Redditor.parse(Reddit reddit, Map data) : super(reddit) {
if (!data.containsKey('name') &&
!(data.containsKey('kind') &&
data['kind'] == Reddit.defaultRedditorKind)) {
throw DRAWArgumentError("input argument 'data' is not a valid"
' representation of a Redditor');
}
setData(this, data);
_name = data['name'];
_path = apiPath['user'].replaceAll(RedditorRef._userRegExp, _name);
}
}
/// A lazily initialized class representing a particular Reddit user, also
/// known as a Redditor. Can be promoted to a [Redditor].
class RedditorRef extends RedditBase
with
BaseListingMixin,
GildedListingMixin,
MessageableMixin,
RedditorListingMixin {
static final _subredditRegExp = RegExp(r'{subreddit}');
static final _userRegExp = RegExp(r'{user}');
static final _usernameRegExp = RegExp(r'{username}');
/// The Redditor's display name (e.g., spez or XtremeCheese).
@override
String get displayName => _name;
late String _name;
/// The Reddit path suffix for this Redditor (e.g., 'user/spez/')
@override
String get path => _path;
late String _path;
RedditorRef(Reddit reddit) : super(reddit);
RedditorRef.name(Reddit reddit, String name)
: _name = name,
_path = apiPath['user'].replaceAll(_userRegExp, name),
super.withPath(reddit, RedditorRef._generateInfoPath(name));
static String _generateInfoPath(String name) =>
apiPath['user_about'].replaceAll(_userRegExp, name);
Future _throwOnInvalidRedditor(Function f) async {
try {
return await f();
} on DRAWNotFoundException catch (_) {
throw DRAWInvalidRedditorException(displayName);
}
}
/// Adds the [Redditor] as a friend. [note] is an optional string that is
/// associated with the friend entry. Providing [note] requires Reddit Gold.
Future<void> friend({String note = ''}) async =>
_throwOnInvalidRedditor(() async => await reddit.put(
apiPath['friend_v1'].replaceAll(_userRegExp, _name),
body: {'note': note}));
/// Returns a [Redditor] object with friend information populated.
///
/// Friend fields include those such as [note]. Other fields may not be
/// completely initialized.
Future<Redditor> friendInfo() async =>
(await _throwOnInvalidRedditor(() async => await reddit.get(
apiPath['friend_v1'].replaceAll(_userRegExp, _name)))) as Redditor;
/// Gives Reddit Gold to the [Redditor]. [months] is the number of months of
/// Reddit Gold to be given to the [Redditor].
///
/// Throws a [DRAWGildingError] if the [Redditor] has insufficient gold
/// creddits.
Future<void> gild({int months = 1}) async {
final body = {
'username': _name,
'months': months.toString(),
};
final path = Uri.https(Reddit.defaultOAuthApiEndpoint,
apiPath['gild_user'].replaceAll(_usernameRegExp, _name));
final result = await _throwOnInvalidRedditor(
() async => await reddit.auth.post(path, body));
if (result is Map) {
throw DRAWGildingException(result.cast<String, String>());
}
}
/// Returns a [List] of the [Redditor]'s public [Multireddit]'s.
Future<List<Multireddit>> multireddits() async =>
(await _throwOnInvalidRedditor(() async => await reddit
.get(apiPath['multireddit_user'].replaceAll(_userRegExp, _name))))
.cast<Multireddit>();
/// Promotes this [RedditorRef] into a populated [Redditor].
Future<Redditor> populate() async =>
((await _throwOnInvalidRedditor(() async =>
Redditor.parse(reddit, (await fetch()) as Map<dynamic, dynamic>)))
as Redditor?)!;
// TODO(bkonyi): Add code samples.
/// Provides a [RedditorStream] for the current [Redditor].
///
/// [RedditorStream] can be used to retrieve new comments and submissions made
/// by a [Redditor] indefinitely.
RedditorStream get stream => RedditorStream(this);
/// Unblock the [Redditor].
Future<void> unblock() async {
final currentUser = (await reddit.user.me()) as Redditor;
final data = {
'container': 't2_' + currentUser.data!['id'],
'name': displayName,
'type': 'enemy',
};
await _throwOnInvalidRedditor(() async => await reddit.post(
apiPath['unfriend'].replaceAll(RedditorRef._subredditRegExp, 'all'),
data,
discardResponse: true));
}
/// Unfriend the [Redditor].
Future<void> unfriend() async => await _throwOnInvalidRedditor(() async =>
await reddit.delete(apiPath['friend_v1'].replaceAll(_userRegExp, _name)));
/// Returns a list of [Trophy] that this [Redditor] has
Future<List<Trophy>> trophies() async {
final response = await reddit.get(
apiPath['trophies'].replaceAll(RedditorRef._usernameRegExp, _name));
return List.castFrom<dynamic, Trophy>(response);
}
}
/// Provides [Comment] and [Submission] streams for a particular [Redditor].
class RedditorStream extends RedditBase {
final RedditorRef redditor;
RedditorStream(this.redditor) : super(redditor.reddit);
/// Returns a [Stream<Comment>] which listens for new comments as they become
/// available.
///
/// Comments are streamed oldest first, and up to 100 historical comments will
/// be returned initially. If [limit] is provided, the stream will close after
/// after [limit] iterations. If [pauseAfter] is provided, null will be
/// returned after [pauseAfter] requests without new items.
Stream<Comment?> comments({int? limit, int? pauseAfter}) =>
streamGenerator(redditor.comments.newest,
itemLimit: limit, pauseAfter: pauseAfter);
/// Returns a [Stream<Submissions>] which listens for new submissions as they
/// become available.
///
/// Submissions are streamed oldest first, and up to 100 historical
/// submissions will be returned initially. If [limit] is provided,
/// the stream will close after after [limit] iterations. If [pauseAfter] is
/// provided, null will be returned after [pauseAfter] requests without new
/// items.
Stream<Submission?> submissions({int? limit, int? pauseAfter}) =>
streamGenerator(redditor.submissions.newest,
itemLimit: limit, pauseAfter: pauseAfter);
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/subreddits.dart | // Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/listing/listing_generator.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/util.dart';
/// Contains functionality which allows for querying information related to
/// Subreddits.
class Subreddits {
static final RegExp _kSubredditsRegExp = RegExp(r'{subreddits}');
final Reddit reddit;
Subreddits(this.reddit);
/// Returns a [Stream] of default subreddits.
Stream<SubredditRef> defaults({int? limit, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(
reddit, apiPath['subreddits_default'],
limit: limit, params: params);
/// Returns a [Stream] of gold subreddits.
Stream<SubredditRef> gold({int? limit, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, apiPath['subreddits_gold'],
limit: limit, params: params);
/// Returns a [Stream] of new subreddits.
Stream<SubredditRef> newest({int? limit, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, apiPath['subreddits_new'],
limit: limit, params: params);
/// Returns a [Stream] of popular subreddits.
Stream<SubredditRef> popular({int? limit, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(
reddit, apiPath['subreddits_popular'],
limit: limit, params: params);
/// Returns a [List] of subreddit recommendedations based on the given list
/// of subreddits.
///
/// `subreddits` is a list of [SubredditRef]s and/or subreddit names as
/// [String]s. `omitSubreddits` is a list of [SubredditRef]s and/or subreddit
/// names as [String]s which are to be excluded from the results.
Future<List<SubredditRef>> recommended(List subreddits,
{List? omitSubreddits}) async {
String subredditsToString(List? subs) {
if (subs == null) {
return '';
}
final strings = <String>[];
for (final s in subs) {
if (s is SubredditRef) {
strings.add(s.displayName);
} else if (s is String) {
strings.add(s);
} else {
throw DRAWArgumentError('A subreddit list must contain either '
'instances of SubredditRef or String. Got type: ${s.runtimeType}.');
}
}
return strings.join(',');
}
final params = <String, String>{'omit': subredditsToString(omitSubreddits)};
final url = apiPath['sub_recommended']
.replaceAll(_kSubredditsRegExp, subredditsToString(subreddits));
return <SubredditRef>[
for (final sub
in (await reddit.get(url, params: params, objectify: false))
.cast<Map>())
SubredditRef.name(reddit, sub['sr_name'])
];
}
/// Returns a [Stream] of subreddits matching `query`.
///
/// This search is performed using both the title and description of
/// subreddits. To search solely by name, see [Subreddits.searchByName].
Stream<SubredditRef> search(String query,
{int? limit, Map<String, String>? params}) {
params ??= <String, String>{};
params['q'] = query;
return ListingGenerator.createBasicGenerator(
reddit, apiPath['subreddits_search'],
limit: limit, params: params);
}
/// Returns a [List<SubredditRef>] of subreddits whose names being with
/// `query`.
///
/// If `includeNsfw` is true, NSFW subreddits will be included in the
/// results. If `exact` is true, only results which are directly matched by
/// `query` will be returned.
Future<List<SubredditRef>> searchByName(String query,
{bool includeNsfw = true, bool exact = false}) async {
final params = <String, String>{};
params['query'] = query;
params['exact'] = exact.toString();
params['include_over_18'] = includeNsfw.toString();
return <SubredditRef>[
for (final s in (await reddit.post(
apiPath['subreddits_name_search'], params,
objectify: false))['names'])
reddit.subreddit(s)
];
}
/// Returns a [Stream] which is populated as new subreddits are created.
Stream<SubredditRef?> stream({int? limit, int? pauseAfter}) =>
streamGenerator(newest, itemLimit: limit, pauseAfter: pauseAfter);
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/trophy.dart | import 'package:draw/draw.dart';
import 'package:draw/src/base_impl.dart';
/// A Class representing an award or trophy
class Trophy extends RedditBase with RedditBaseInitializedMixin {
Trophy.parse(Reddit reddit, Map? data) : super(reddit) {
setData(this, data);
}
/// The ID of the [Trophy] (Can be None).
String? get awardId => data!['award_id'];
/// The description of the [Trophy] (Can be None).
String? get description => data!['description'];
/// The URL of a 41x41 px icon for the [Trophy].
String? get icon_40 => data!['icon_40'];
/// The URL of a 71x71 px icon for the [Trophy].
String? get icon_70 => data!['icon_70'];
/// The name of the [Trophy].
String? get name => data!['name'];
/// A relevant URL (Can be None).
String? get url => data!['url'];
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/submission_impl.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/getter_utils.dart';
import 'package:draw/src/logging.dart';
import 'package:draw/src/models/comment_forest.dart';
import 'package:draw/src/models/comment_impl.dart';
import 'package:draw/src/models/flair.dart';
import 'package:draw/src/models/mixins/editable.dart';
import 'package:draw/src/models/mixins/gildable.dart';
import 'package:draw/src/models/mixins/inboxable.dart';
import 'package:draw/src/models/mixins/inboxtoggleable.dart';
import 'package:draw/src/models/mixins/replyable.dart';
import 'package:draw/src/models/mixins/reportable.dart';
import 'package:draw/src/models/mixins/saveable.dart';
import 'package:draw/src/models/mixins/user_content_mixin.dart';
import 'package:draw/src/models/mixins/user_content_moderation.dart';
import 'package:draw/src/models/mixins/voteable.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/models/user_content.dart';
import 'package:draw/src/reddit.dart';
final Logger _logger = Logger('Submission');
Comment? getCommentByIdInternal(SubmissionRef s, String id) {
if (s._commentsById.containsKey(id)) {
return s._commentsById[id];
}
return null;
}
void insertCommentById(SubmissionRef s, /*Comment, MoreComments*/ c) {
assert((c is Comment) || (c is MoreComments));
_logger.info(
'insertCommentById: Comment(id:${c.fullname}) Submission(id:${s._id},hash:${s.hashCode})');
s._commentsById[c.fullname] = c;
if ((c is Comment) && (c.replies != null)) {
for (final reply in c.replies!.toList()) {
if (reply is Comment) {
s._commentsById[reply.fullname] = reply;
}
}
}
}
/// A fully initialized representation of a standard Reddit submission.
class Submission extends SubmissionRef
with
RedditBaseInitializedMixin,
UserContentInitialized,
EditableMixin,
GildableMixin,
InboxableMixin,
InboxToggleableMixin,
ReplyableMixin,
ReportableMixin,
SaveableMixin,
VoteableMixin {
/// The sorting method that this [Submission] will use when retrieving comments.
///
/// Defaults to [CommentSortType.best].
CommentSortType _commentSort = CommentSortType.best;
CommentSortType get commentSort => _commentSort;
/// The date and time that this [Submission] was approved.
///
/// Returns `null` if the [Submission] has not been approved.
DateTime? get approvedAt => (data!['approved_at_utc'] == null)
? null
: DateTime.fromMillisecondsSinceEpoch(
data!['approved_at_utc'].round() * 1000);
/// Has this [Submission] been approved.
bool? get approved => data!['approved'];
/// A [RedditorRef] of the [Redditor] who approved this [Submission]
///
/// Returns `null` if the [Submission] has not been approved.
RedditorRef? get approvedBy =>
GetterUtils.redditorRefOrNull(reddit, data!['approved_by']);
/// Is this [Submission] archived.
bool get archived => data!['archived'];
/// The author's flair text, if set.
///
/// If the author does not have flair text set, this property is `null`.
String? get authorFlairText => data!['author_flair_text'];
/// The date and time that this [Submission] was banned.
///
/// Returns `null` if the [Submission] has not been approved.
DateTime? get bannedAt => GetterUtils.dateTimeOrNull(data!['banned_at_utc']);
/// A [RedditorRef] of the [Redditor] who banned this [Submission].
///
/// Returns `null` if the [Submission] has not been banned.
RedditorRef? get bannedBy =>
GetterUtils.redditorRefOrNull(reddit, data!['banned_by']);
/// Is this [Submission] considered 'brand-safe' by Reddit.
bool? get brandSafe => data!['brand_safe'];
/// Can this [Submission] be awarded Reddit Gold.
bool get canGild => data!['can_gild'];
/// Can this [Submission] be moderated by the currently authenticated [Redditor].
bool? get canModeratePost => data!['can_mod_post'];
/// Has this [Submission] been clicked.
bool get clicked => data!['clicked'];
/// Returns the [CommentForest] representing the comments for this
/// [Submission]. May be null (see [refreshComments]).
CommentForest? get comments => _comments;
/// Repopulates the [CommentForest] with the most up-to-date comments.
///
/// Note: some methods of generating [Submission] objects do not populate the
/// `comments` property, resulting in it being set to `null`. This method can
/// also be used to populate `comments`.
Future<CommentForest> refreshComments(
{CommentSortType sort = CommentSortType.best}) async {
_commentSort = sort;
final response = await fetch();
_comments = CommentForest(this, response[1]['listing']);
return _comments!;
}
@override
Map<String, String>? get infoParams {
if (commentSort != CommentSortType.best) {
return {'sort': commentSortTypeToString(commentSort)};
}
return null;
}
/// Is this [Submission] in contest mode.
bool get contestMode => data!['contest_mode'];
/// The time this [Submission] was created.
DateTime get createdUtc => GetterUtils.dateTimeOrNull(data!['created_utc'])!;
/// Is this [Submission] distinguished.
///
/// For example, if a moderator creates a post and chooses to show that it was
/// created by a moderator, this property will be set to 'moderator'. If this
/// [Submission] is not distinguished, this property is `null`.
String? get distinguished => data!['distinguished'];
/// Returns the domain of this [Submission].
///
/// For self-text [Submission]s, domains take the form of 'self.announcements'.
/// For link [Submission]s, domains take the form of 'github.com'.
String get domain => data!['domain'];
/// The number of downvotes for this [Submission].
int get downvotes => data!['downs'];
/// Has this [Submission] been edited.
bool get edited => (data!['edited'] is double);
SubmissionFlair? _flair;
/// Helper utilities to manage flair for this [Submission].
SubmissionFlair get flair {
_flair ??= SubmissionFlair._(this);
return _flair!;
}
/// Is this [Submission] marked as hidden.
bool get hidden => data!['hidden'];
/// Is the score of this [Submission] hidden.
bool get hideScore => data!['hide_score'];
/// Ignore reports for this [Submission].
bool? get ignoreReports => data!['ignore_reports'];
/// Can this [Submission] be cross-posted.
bool get isCrosspostable => data!['is_crosspostable'];
/// Is this [Submission] hosted on a Reddit media domain.
bool get isRedditMediaDomain => data!['is_reddit_media_domain'];
/// Is this [Submission] a self-post.
///
/// Self-posts are [Submission]s that consist solely of text.
bool get isSelf => data!['is_self'];
/// Is this [Submission] a video.
bool get isVideo => data!['is_video'];
/// Text of the flair set for this [Submission].
///
/// May return `null` if the submission has no flair.
String? get linkFlairText => data!['link_flair_text'];
/// Has this [Submission] been locked.
bool get locked => data!['locked'];
/// The number of [Comment]s made on this [Submission].
int get numComments => data!['num_comments'];
/// The number of times this [Submission] has been cross-posted.
int get numCrossposts => data!['num_crossposts'];
/// Is this [Submission] restricted to [Redditor]s 18+.
bool get over18 => data!['over_18'];
/// The preview images for this [Submission].
///
/// Returns an empty list if the [Submission] does not have a preview image.
List<SubmissionPreview> get preview {
final previews = <SubmissionPreview>[];
if (!data!.containsKey('preview')) {
return previews;
}
assert(data!['preview'].containsKey('images'));
final raw = data!['preview']['images'].cast<Map<String, dynamic>>();
for (final i in raw) {
previews.add(SubmissionPreview._fromMap(i));
}
return previews;
}
/// The variations of images for this [Submission] as a [List<Map<String,SubmissionPreview>>].
///
/// eg: [{"gif": [SubmissionPreview]}]
///
/// Returns an empty List if the [Submission] does not have any image variations.
List<Map<String, SubmissionPreview>> get variants {
final List<Map<String?, SubmissionPreview>> previews =
<Map<String, SubmissionPreview>>[];
if (!data!.containsKey('preview')) {
return previews as List<Map<String, SubmissionPreview>>;
}
assert(data!['preview'].containsKey('images'));
final raw = data!['preview']['images'].cast<Map<String, dynamic>>();
for (final image in raw) {
if (image.containsKey('variants')) {
final _variants = image['variants'];
for (final variant in _variants.keys) {
previews
.add({variant: SubmissionPreview._fromMap(_variants[variant])});
}
}
}
return previews as List<Map<String, SubmissionPreview>>;
}
/// Is this [Submission] pinned.
bool get pinned => data!['pinned'];
/// Is this [Submission] in quarantine.
bool get quarantine => data!['quarantine'];
/// The reason why this [Submission] was removed.
///
/// Returns `null` if the [Submission] has not been removed.
String? get removalReason => data!['removal_reason'];
/// Has this [Submission] been removed.
bool get removed => data!['removed'];
/// Is this [Submission] saved.
@override
bool get saved => data!['saved'];
/// The current score (net upvotes) for this [Submission].
@override
int get score => data!['score'];
/// The text body of a self-text post.
///
/// Returns null if the [Submission] is not a self-text submission.
String? get selftext => data!['selftext'];
/// Is this [Submission] marked as spam.
bool? get spam => data!['spam'];
/// Does this [Submission] contain a spoiler.
bool get spoiler => data!['spoiler'];
/// A [SubredditRef] of the [Subreddit] this [Submission] was made in.
SubredditRef get subreddit => reddit.subreddit(data!['subreddit']);
/// The type of the [Subreddit] this [Submission] was made in.
///
/// For example, if a [Subreddit] is restricted to approved submitters, this
/// property will be 'restricted'.
String get subredditType => data!['subreddit_type'];
/// Has this [Submission] been stickied.
bool get stickied => data!['stickied'];
/// The title of the [Submission].
String get title => data!['title'];
/// The Uri of the [Submission]'s thumbnail image.
Uri get thumbnail => Uri.parse(data!['thumbnail']);
/// The ratio of upvotes to downvotes for this [Submission].
double get upvoteRatio => data!['upvote_ratio'];
/// The number of upvotes this [Submission] has received.
int get upvotes => data!['ups'];
/// The URL of the [Submission]'s link.
Uri get url => Uri.parse(data!['url']!);
/// The number of views this [Submission] has.
int get viewCount => data!['view_count'];
/// Has this [Submission] been visited by the current [User].
bool? get visited => data!['visited'];
SubmissionModeration get mod {
_mod ??= SubmissionModeration._(this);
return _mod!;
}
SubmissionModeration? _mod;
Submission.parse(Reddit reddit, Map data)
: super.withPath(reddit, SubmissionRef._infoPath(data['id'])) {
setData(this, data);
}
/// Crosspost the submission to another [Subreddit].
///
/// [subreddit] is the subreddit to crosspost the submission to, [title] is
/// the title to be given to the new post (default is the original title), and
/// if [sendReplies] is true (default), replies will be sent to the currently
/// authenticated user's messages.
///
/// Note: crosspost is fairly new on Reddit and is only available to
/// certain users on select subreddits who opted in to the beta. This method
/// does work, but is difficult to test correctly while the feature is in
/// beta. As a result, it's probably best not to use this method until
/// crossposting is out of beta on Reddit (still in beta as of 2017/10/27).
Future<Submission> crosspost(Subreddit subreddit,
{String? title, bool sendReplies = true}) async {
final data = <String, String?>{
'sr': subreddit.displayName,
'title': title ?? this.data!['title'],
'sendreplies': sendReplies.toString(),
'kind': 'crosspost',
'crosspost_fullname': fullname,
'api_type': 'json',
};
return (await reddit.post(apiPath['submit'], data)) as Submission;
}
/// Unhide the submission.
///
/// If provided, [otherSubmissions] is a list of other submissions to be
/// unhidden.
Future<void> unhide({List<Submission>? otherSubmissions}) async {
for (final submissions in _chunk(otherSubmissions, 50)) {
await reddit.post(apiPath['unhide'], {'id': submissions},
discardResponse: true);
}
}
/// Hide the submission.
///
/// If provided, [otherSubmissions] is a list of other submissions to be
/// hidden.
Future<void> hide({List<Submission>? otherSubmissions}) async {
for (final submissions in _chunk(otherSubmissions, 50)) {
await reddit.post(apiPath['hide'], {'id': submissions},
discardResponse: true);
}
}
Iterable<String> _chunk(
List<Submission>? otherSubmissions, int chunkSize) sync* {
final submissions = <String>[fullname!];
if (otherSubmissions != null) {
otherSubmissions.forEach((Submission s) {
submissions.add(s.fullname!);
});
}
for (var i = 0; i < submissions.length; i += chunkSize) {
yield submissions
.getRange(i, min(i + chunkSize, submissions.length))
.join(',');
}
}
}
/// A lazily initialized representation of a standard Reddit submission. Can be
/// promoted to a [Submission].
class SubmissionRef extends UserContent {
static final RegExp _submissionRegExp = RegExp(r'{id}');
CommentForest? _comments;
final String _id;
final Map _commentsById = {};
SubmissionRef.withPath(Reddit reddit, String path)
: _id = idFromUrl(path),
super.withPath(reddit, _infoPath(idFromUrl(path)));
SubmissionRef.withID(Reddit reddit, String id)
: _id = id,
super.withPath(reddit, _infoPath(id));
static String _infoPath(String id) =>
apiPath['submission'].replaceAll(_submissionRegExp, id);
/// The shortened link for the [Submission].
Uri get shortlink => Uri.parse(reddit.config.shortUrl! + _id);
// TODO(bkonyi): allow for paths without trailing '/'.
/// Retrieve a submission ID from a given URL.
///
/// Note: when [url] is a [String], it must end with a trailing '/'. This is a
/// bug and will be fixed eventually.
static String idFromUrl(/*String, Uri*/ url) {
Uri uri;
if (url is String) {
uri = Uri.parse(url);
} else if (url is Uri) {
uri = url;
} else {
throw DRAWArgumentError('idFromUrl expects either a String or Uri as'
' input');
}
var submissionId = '';
final parts = uri.path.split('/');
final commentsIndex = parts.indexOf('comments');
if (commentsIndex == -1) {
submissionId = parts[parts.length - 2];
} else {
submissionId = parts[commentsIndex + 1];
}
return submissionId;
}
// TODO(bkonyi): implement
// Stream duplicates() => throw DRAWUnimplementedError();
/// Promotes this [SubmissionRef] into a populated [Submission].
Future<Submission> populate() async {
try {
final response = await fetch();
final submission = response[0]['listing'][0];
submission._comments = CommentForest(submission, response[1]['listing']);
return submission;
// ignore: unused_catch_clause
} on DRAWNotFoundException catch (e) {
throw DRAWInvalidSubmissionException(_id);
}
}
}
/// A representation of a submission's preview.
class SubmissionPreview {
/// The preview ID.
String get id => _id;
/// A list of preview images scaled to various resolutions.
List<PreviewImage> get resolutions => _resolutions;
/// The original source of the preview image.
PreviewImage get source => _source;
late PreviewImage _source;
late List<PreviewImage> _resolutions;
late String _id;
SubmissionPreview._fromMap(Map<String, dynamic> map) {
final sourceMap = map['source'];
final resolutionsList = map['resolutions'].cast<Map<String, dynamic>>();
assert(sourceMap != null);
assert(resolutionsList != null);
_source = PreviewImage._fromMap(sourceMap);
_resolutions = <PreviewImage>[];
resolutionsList.forEach((e) => _resolutions.add(PreviewImage._fromMap(e)));
_id = map['id'];
}
}
/// A representation of the properties of a [Submission]'s preview image.
class PreviewImage {
final Uri url;
final int width;
final int height;
PreviewImage._fromMap(Map<String, dynamic> map)
: url = Uri.parse(map['url'].replaceAll('amp;', '')),
width = map['width'],
height = map['height'];
}
String commentSortTypeToString(CommentSortType t) {
switch (t) {
case CommentSortType.confidence:
return 'confidence';
case CommentSortType.top:
return 'top';
case CommentSortType.newest:
return 'new';
case CommentSortType.controversial:
return 'controversial';
case CommentSortType.old:
return 'old';
case CommentSortType.random:
return 'random';
case CommentSortType.qa:
return 'qa';
case CommentSortType.blank:
return 'blank';
case CommentSortType.best:
return 'best';
default:
throw DRAWInternalError('CommentSortType: $t is not supported.');
}
}
enum CommentSortType {
confidence,
top,
best,
newest,
controversial,
old,
random,
qa,
blank
}
/// Provides a set of moderation functions for a [Submisson].
class SubmissionModeration extends Object with UserContentModerationMixin {
static final RegExp _subModRegExp = RegExp(r'{subreddit}');
@override
Submission get content => _content;
final Submission _content;
SubmissionModeration._(this._content);
/// Enables contest mode for the [Comment]s in this [Submission].
///
/// If `state` is true (default), contest mode is enabled for this
/// [Submission].
///
/// Contest mode have the following effects:
/// * The comment thread will default to being sorted randomly.
/// * Replies to top-level comments will be hidden behind
/// "[show replies]" buttons.
/// * Scores will be hidden from non-moderators.
/// * Scores accessed through the API (mobile apps, bots) will be
/// obscured to "1" for non-moderators.
Future<void> contestMode({bool state = true}) async => _content.reddit.post(
apiPath['contest_mode'],
{
'id': _content.fullname,
'state': state.toString(),
},
discardResponse: true);
/// Sets the flair for the [Submission].
///
/// `text` is the flair text to be associated with the [Submission].
/// `cssClass` is the CSS class to associate with the flair HTML.
///
/// This method can only be used by an authenticated user who has moderation
/// rights for this [Submission].
Future<void> flair({String text = '', String cssClass = ''}) async {
final data = {
'css_class': cssClass,
'link': _content.fullname,
'text': text,
};
var subreddit = _content.subreddit;
if (subreddit is! Subreddit) {
subreddit = await subreddit.populate();
}
final url =
apiPath['flair'].replaceAll(_subModRegExp, subreddit.displayName);
await _content.reddit.post(url, data, discardResponse: true);
}
/// Locks the [Submission] to new [Comment]s.
Future<void> lock() async => _content.reddit.post(
apiPath['lock'],
{
'id': _content.fullname,
},
discardResponse: true);
/// Marks the [Submission] as not safe for work.
///
/// Both the [Submission] author and users with moderation rights for this
/// submission can set this flag.
Future<void> nsfw() async => _content.reddit.post(
apiPath['marknsfw'],
{
'id': _content.fullname,
},
discardResponse: true);
/// Marks the [Submission] as safe for work.
///
/// Both the [Submission] author and users with moderation rights for this
/// submission can set this flag.
Future<void> sfw() async => _content.reddit.post(
apiPath['unmarknsfw'],
{
'id': _content.fullname,
},
discardResponse: true);
/// Indicate that the submission contains spoilers.
///
/// Both the [Submission] author and users with moderation rights for this
/// submission can set this flag.
Future<void> spoiler() async => _content.reddit.post(
apiPath['spoiler'],
{
'id': _content.fullname,
},
discardResponse: true);
/// Set the [Submission]'s sticky state in its [Subreddit].
///
/// If `state` is `true`, the [Submission] is stickied. If `false`, it is
/// unstickied.
///
/// If `bottom` is `true`, the [Submission] is set as the bottom sticky. If
/// no top sticky exists, this [Submission] will become the top sticky.
Future<void> sticky({bool state = true, bool bottom = true}) async {
final data = <String, String>{
'id': _content.fullname!,
'state': state.toString(),
'api_type': 'json',
};
if (!bottom) {
data['num'] = '1';
}
return _content.reddit.post(apiPath['sticky_submission'], data);
}
/// Sets the suggested [Comment] sorting for the [Submission].
///
/// Defaults to [CommentSortType.blank].
Future<void> suggestedSort({CommentSortType sort = CommentSortType.blank}) =>
_content.reddit.post(
apiPath['suggested_sort'],
{
'id': _content.fullname,
'sort': commentSortTypeToString(sort),
},
discardResponse: true);
/// Unlocks the [Submission] to allow for new [Comment]s.
Future<void> unlock() async => _content.reddit.post(
apiPath['unlock'],
{
'id': _content.fullname,
},
discardResponse: true);
/// Indicate that the submission contains spoilers.
///
/// Both the [Submission] author and users with moderation rights for this
/// submission can set this flag.
Future<void> unspoiler() async => _content.reddit.post(
apiPath['unspoiler'],
{
'id': _content.fullname,
},
discardResponse: true);
}
/// Provides functionality for setting flair for this [Submission].
class SubmissionFlair {
final RegExp _kSubredditRegExp = RegExp('{subreddit}');
final Submission _submission;
SubmissionFlair._(this._submission);
/// The list of available [FlairTemplate]s for this [Submission].
Future<List<FlairTemplate>> choices() async {
final url = apiPath['flairselector']
.replaceAll(_kSubredditRegExp, _submission.subreddit.displayName);
final List rawChoices =
(await _submission.reddit.post(url, <String, String>{
'link': _submission.fullname!,
}))['choices'];
final choices = <FlairTemplate>[];
rawChoices.forEach((e) => choices.add(FlairTemplate.parse(e)));
return choices;
}
/// Sets the flair for the current [Submission].
///
/// `flairTemplateId` is the name of the [FlairTemplate] retrieved from
/// `choices()`. If the [FlairTemplate] allows for editable text, providing
/// `text` will be set as the custom text. `text` must be shorter than 64
/// characters.
Future<void> select(String flairTemplateId, {String text = ''}) async {
if (text.length > 64) {
throw DRAWArgumentError("Argument 'text' must not be longer than"
' 64 characters');
}
final data = <String, String>{
'flair_template_id': flairTemplateId,
'link': _submission.fullname!,
'text': text,
};
final url = apiPath['select_flair']
.replaceAll(_kSubredditRegExp, _submission.subreddit.displayName);
await _submission.reddit.post(url, data, discardResponse: true);
}
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/subreddit_moderation.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/listing/listing_generator.dart';
import 'package:draw/src/models/message.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/models/user_content.dart';
import 'package:draw/src/reddit.dart';
String subredditTypeToString(SubredditType type) {
switch (type) {
case SubredditType.archivedSubreddit:
return 'archived';
case SubredditType.employeesOnlySubreddit:
return 'employees_only';
case SubredditType.goldOnlySubreddit:
return 'gold_only';
case SubredditType.goldRestrictedSubreddit:
return 'gold_restricted';
case SubredditType.privateSubreddit:
return 'private';
case SubredditType.publicSubreddit:
return 'public';
case SubredditType.restrictedSubreddit:
return 'restricted';
default:
throw DRAWInternalError('Invalid subreddit type: $type.');
}
}
SubredditType stringToSubredditType(String s) {
switch (s) {
case 'archived':
return SubredditType.archivedSubreddit;
case 'employees_only':
return SubredditType.employeesOnlySubreddit;
case 'gold_only':
return SubredditType.goldOnlySubreddit;
case 'gold_restricted':
return SubredditType.goldRestrictedSubreddit;
case 'private':
return SubredditType.privateSubreddit;
case 'public':
return SubredditType.publicSubreddit;
case 'restricted':
return SubredditType.restrictedSubreddit;
default:
throw DRAWInternalError('Invalid subreddit type: $s.');
}
}
enum SubredditType {
archivedSubreddit,
employeesOnlySubreddit,
goldOnlySubreddit,
goldRestrictedSubreddit,
privateSubreddit,
publicSubreddit,
restrictedSubreddit,
}
enum ModeratorActionType {
acceptModeratorInvite,
addContributor,
addModerator,
approveComment,
approveLink,
banUser,
communityStyling,
communityWidgets,
createRule,
deleteRule,
distinguish,
editFlair,
editRule,
editSettings,
ignoreReports,
inviteModerator,
lock,
markNSFW,
modmailEnrollment,
muteUser,
removeComment,
removeContributor,
removeLink,
removeModerator,
removeWikiContributor,
setContestMode,
setPermissions,
setSuggestedSort,
spamComment,
spamLink,
spoiler,
sticky,
unbanUser,
unignoreReports,
uninviteModerator,
unlock,
unmuteUser,
unsetContestMode,
unspoiler,
unsticky,
wikiBanned,
wikiContributor,
wikiPageListed,
wikiPermLevel,
wikiRevise,
wikiUnbanned,
}
enum SpamSensitivity { all, low, high }
enum WikiAccessMode { anyone, disabled, modonly }
enum PostContentType { any, link, self }
enum SuggestedCommentSort {
confidence,
controversial,
live,
newest,
old,
qa,
random,
top,
}
String moderatorActionTypesToString(ModeratorActionType a) {
switch (a) {
case ModeratorActionType.acceptModeratorInvite:
return 'acceptmoderatorinvite';
case ModeratorActionType.addContributor:
return 'addcontributor';
case ModeratorActionType.addModerator:
return 'addmoderator';
case ModeratorActionType.approveComment:
return 'approvecomment';
case ModeratorActionType.approveLink:
return 'approvelink';
case ModeratorActionType.banUser:
return 'banuser';
case ModeratorActionType.communityStyling:
return 'community_styling';
case ModeratorActionType.communityWidgets:
return 'community_widgets';
case ModeratorActionType.createRule:
return 'createrule';
case ModeratorActionType.deleteRule:
return 'deleterule';
case ModeratorActionType.distinguish:
return 'distinguish';
case ModeratorActionType.editFlair:
return 'editflair';
case ModeratorActionType.editRule:
return 'editrule';
case ModeratorActionType.editSettings:
return 'editsettings';
case ModeratorActionType.ignoreReports:
return 'ignorereports';
case ModeratorActionType.inviteModerator:
return 'invitemoderator';
case ModeratorActionType.lock:
return 'lock';
case ModeratorActionType.markNSFW:
return 'marknsfw';
case ModeratorActionType.modmailEnrollment:
return 'modmail_enrollment';
case ModeratorActionType.muteUser:
return 'muteuser';
case ModeratorActionType.removeComment:
return 'removecomment';
case ModeratorActionType.removeContributor:
return 'removecontributor';
case ModeratorActionType.removeLink:
return 'removelink';
case ModeratorActionType.removeModerator:
return 'removemoderator';
case ModeratorActionType.removeWikiContributor:
return 'removewikicontributor';
case ModeratorActionType.setContestMode:
return 'setcontestmode';
case ModeratorActionType.setPermissions:
return 'setpermissions';
case ModeratorActionType.setSuggestedSort:
return 'setsuggestedsort';
case ModeratorActionType.spamComment:
return 'spamcomment';
case ModeratorActionType.spamLink:
return 'spamlink';
case ModeratorActionType.spoiler:
return 'spoiler';
case ModeratorActionType.sticky:
return 'sticky';
case ModeratorActionType.unbanUser:
return 'unbanuser';
case ModeratorActionType.unignoreReports:
return 'unignorereports';
case ModeratorActionType.uninviteModerator:
return 'uninvitemoderator';
case ModeratorActionType.unlock:
return 'unlock';
case ModeratorActionType.unmuteUser:
return 'unmuteuser';
case ModeratorActionType.unsetContestMode:
return 'unsetcontestmode';
case ModeratorActionType.unspoiler:
return 'unspoiler';
case ModeratorActionType.unsticky:
return 'unsticky';
case ModeratorActionType.wikiBanned:
return 'wikibanned';
case ModeratorActionType.wikiContributor:
return 'wikicontributor';
case ModeratorActionType.wikiPageListed:
return 'wikipagelisted';
case ModeratorActionType.wikiPermLevel:
return 'wikipermlevel';
case ModeratorActionType.wikiRevise:
return 'wikirevise';
case ModeratorActionType.wikiUnbanned:
return 'wikiunbanned';
default:
throw DRAWInternalError('Invalid moderator action type: $a.');
}
}
ModeratorActionType stringToModeratorActionType(String s) {
switch (s) {
case 'acceptmoderatorinvite':
return ModeratorActionType.acceptModeratorInvite;
case 'addcontributor':
return ModeratorActionType.addContributor;
case 'addmoderator':
return ModeratorActionType.addModerator;
case 'approvecomment':
return ModeratorActionType.approveComment;
case 'approvelink':
return ModeratorActionType.approveLink;
case 'banuser':
return ModeratorActionType.banUser;
case 'community_styling':
return ModeratorActionType.communityStyling;
case 'community_widgets':
return ModeratorActionType.communityWidgets;
case 'createrule':
return ModeratorActionType.createRule;
case 'deleterule':
return ModeratorActionType.deleteRule;
case 'distinguish':
return ModeratorActionType.distinguish;
case 'editflair':
return ModeratorActionType.editFlair;
case 'editrule':
return ModeratorActionType.editRule;
case 'editsettings':
return ModeratorActionType.editSettings;
case 'ignorereports':
return ModeratorActionType.ignoreReports;
case 'invitemoderator':
return ModeratorActionType.inviteModerator;
case 'lock':
return ModeratorActionType.lock;
case 'marknsfw':
return ModeratorActionType.markNSFW;
case 'modmail_enrollment':
return ModeratorActionType.modmailEnrollment;
case 'muteuser':
return ModeratorActionType.muteUser;
case 'removecomment':
return ModeratorActionType.removeComment;
case 'removecontributor':
return ModeratorActionType.removeContributor;
case 'removelink':
return ModeratorActionType.removeLink;
case 'removemoderator':
return ModeratorActionType.removeModerator;
case 'removewikicontributor':
return ModeratorActionType.removeWikiContributor;
case 'setcontestmode':
return ModeratorActionType.setContestMode;
case 'setpermissions':
return ModeratorActionType.setPermissions;
case 'setsuggestedsort':
return ModeratorActionType.setSuggestedSort;
case 'spamcomment':
return ModeratorActionType.spamComment;
case 'spamlink':
return ModeratorActionType.spamLink;
case 'spoiler':
return ModeratorActionType.spoiler;
case 'sticky':
return ModeratorActionType.sticky;
case 'unbanuser':
return ModeratorActionType.unbanUser;
case 'unignorereports':
return ModeratorActionType.unignoreReports;
case 'uninvitemoderator':
return ModeratorActionType.uninviteModerator;
case 'unlock':
return ModeratorActionType.unlock;
case 'unmuteuser':
return ModeratorActionType.unmuteUser;
case 'unsetcontestmode':
return ModeratorActionType.unsetContestMode;
case 'unspoiler':
return ModeratorActionType.unspoiler;
case 'unsticky':
return ModeratorActionType.unsticky;
case 'wikibanned':
return ModeratorActionType.wikiBanned;
case 'wikicontributor':
return ModeratorActionType.wikiContributor;
case 'wikipagelisted':
return ModeratorActionType.wikiPageListed;
case 'wikipermlevel':
return ModeratorActionType.wikiPermLevel;
case 'wikirevise':
return ModeratorActionType.wikiRevise;
case 'wikiunbanned':
return ModeratorActionType.wikiUnbanned;
default:
throw DRAWInternalError('Invalid moderator action type: $s.');
}
}
SpamSensitivity stringToSpamSensitivity(String s) {
switch (s) {
case 'all':
return SpamSensitivity.all;
case 'low':
return SpamSensitivity.low;
case 'high':
return SpamSensitivity.high;
default:
throw DRAWInternalError('Invalid spam sensitivity type: $s.');
}
}
WikiAccessMode stringToWikiAccessMode(String s) {
switch (s) {
case 'anyone':
return WikiAccessMode.anyone;
case 'modonly':
return WikiAccessMode.modonly;
case 'disabled':
return WikiAccessMode.disabled;
default:
throw DRAWInternalError('Invalid Wiki Access Mode: $s.');
}
}
PostContentType stringToContentType(String s) {
switch (s) {
case 'any':
return PostContentType.any;
case 'self':
return PostContentType.self;
case 'link':
return PostContentType.link;
default:
throw DRAWInternalError('Invalid Post Content type: $s.');
}
}
SuggestedCommentSort? stringToSuggestedCommentSort(String? s) {
if (s == null) {
return null;
}
switch (s) {
case 'confidence':
return SuggestedCommentSort.confidence;
case 'controversial':
return SuggestedCommentSort.controversial;
case 'live':
return SuggestedCommentSort.live;
case 'new':
return SuggestedCommentSort.newest;
case 'old':
return SuggestedCommentSort.old;
case 'qa':
return SuggestedCommentSort.qa;
case 'random':
return SuggestedCommentSort.random;
case 'top':
return SuggestedCommentSort.top;
default:
throw DRAWInternalError('Invalid Suggested Comment Sort: $s.');
}
}
/// A structure which represents the settings of a [Subreddit].
///
/// Any [Subreddit] settings changed here will not be applied unless
/// [SubredditModeration.update] is called with the updated [SubredditSettings].
class SubredditSettings {
final Map _data;
final SubredditRef subreddit;
SubredditSettings.copy(SubredditSettings original)
: _data = Map.from(original._data),
subreddit = original.subreddit;
SubredditSettings._(this.subreddit, this._data);
bool get defaultSet => _data['default_set'];
set defaultSet(bool x) => _data['default_set'] = x;
bool get allowImages => _data['allow_images'];
set allowImages(bool x) => _data['allow_images'] = x;
bool get allowFreeformReports => _data['free_form_reports'];
set allowFreeformReports(bool x) => _data['free_form_reports'] = x;
bool get showMedia => _data['show_media'];
set showMedia(bool x) => _data['show_media'] = x;
/// Age required to edit wiki
int get wikiEditAge => _data['wiki_edit_age'];
set wikiEditAge(int x) => _data['wiki_edit_age'] = x;
String get submitText => _data['submit_text'];
set submitText(String x) => _data['submit_text'] = x;
/// Returns the filter strength set for spam links for subreddit.
SpamSensitivity get spamLinks => stringToSpamSensitivity(_data['spam_links']);
String get title => _data['title'];
set title(String x) => _data['title'] = x;
bool get collapseDeletedComments => _data['collapse_deleted_comments'];
set collapseDeletedComments(bool x) => _data['collapse_deleted_comments'] = x;
/// Returns who can access wiki mode.
WikiAccessMode get wikimode => stringToWikiAccessMode(_data['wikimode']);
/// Whether the traffic stats are visible publicly.
bool get publicTraffic => _data['public_traffic'];
set publicTraffic(bool x) => _data['public_traffic'] = x;
bool get over18 => _data['over_18'];
set over18(bool x) => _data['over_18'] = x;
bool get allowVideos => _data['allow_videos'];
set allowVideos(bool x) => _data['allow_videos'] = x;
bool get spoilersEnabled => _data['spoilers_enabled'];
set spoilersEnabled(bool x) => _data['spoilers_enabled'] = x;
/// The comment sorting method to choose by default.
SuggestedCommentSort? get suggestedCommentSort =>
stringToSuggestedCommentSort(_data['suggested_comment_sort']);
String? get description => _data['description'];
set description(String? x) => _data['description'] = x;
/// Custom label for submit link button.
String? get submitLinkLabel => _data['submit_link_label'];
set submitLinkLabel(String? x) => _data['submit_link_label'] = x;
bool get allowPostCrossposts => _data['allow_post_crossposts'];
set allowPostCrossposts(bool x) => _data['allow_post_crossposts'] = x;
/// Filter strength for comments.
SpamSensitivity get spamComments =>
stringToSpamSensitivity(_data['spam_comments']);
/// Filter strength for self posts.
SpamSensitivity get spamSelfposts =>
stringToSpamSensitivity(_data['spam_selfposts']);
/// Custom label for submit text post button.
String? get submitTextLabel => _data['submit_text_label'];
set submitTextLabel(String? x) => _data['submit_text_label'] = x;
// TODO(bkonyi): we might want to use a color class for this.
// get keyColor => _data['key_color'];
String get language => _data['language'];
set language(String x) => _data['language'] = x;
/// Karma required to edit wiki.
int get wikiEditKarma => _data['wiki_edit_karma'];
set wikiEditKarma(int x) => _data['wiki_edit_karma'] = x;
bool get hideAds => _data['hide_ads'];
set hideAds(bool x) => _data['hide_ads'] = x;
String get headerHoverText => _data['header_hover_text'];
set headerHoverText(String x) => _data['header_hover_text'] = x;
bool get allowDiscovery => _data['allow_discovery'];
set allowDiscovery(bool x) => _data['allow_discovery'] = x;
String? get publicDescription => _data['public_description'];
set publicDescription(String? x) => _data['public_description'] = x;
bool get showMediaPreview => _data['show_media_preview'];
set showMediaPreview(bool x) => _data['show_media_preview'] = x;
int get commentScoreHideMins => _data['comment_score_hide_mins'];
set commentScoreHideMins(int x) => _data['comment_score_hide_mins'] = x;
SubredditType get subredditType =>
stringToSubredditType(_data['subreddit_type']);
set subredditType(SubredditType type) {
_data['subreddit_type'] = subredditTypeToString(type);
}
bool get excludeBannedModQueue => _data['exclude_banned_modqueue'];
set excludeBannedModQueue(bool x) => _data['exclude_banned_modqueue'] = x;
/// Which post types users can use.
PostContentType get contentOptions =>
stringToContentType(_data['content_options']);
@override
String toString() {
final encoder = JsonEncoder.withIndent(' ');
return encoder.convert(_data);
}
}
enum SubredditModerationContentTypeFilter {
commentsOnly,
submissionsOnly,
}
ModeratorAction buildModeratorAction(Reddit reddit, Map data) =>
ModeratorAction._(reddit, data);
/// Represents an action taken by a moderator.
class ModeratorAction {
final Reddit _reddit;
final Map data;
ModeratorAction._(this._reddit, this.data);
ModeratorActionType get action => stringToModeratorActionType(data['action']);
RedditorRef get mod => _reddit.redditor(data['mod']);
SubredditRef get subreddit => _reddit.subreddit(data['subreddit']);
@override
String toString() {
final encoder = JsonEncoder.withIndent(' ');
return encoder.convert(data);
}
}
/// Provides a set of moderation functions to a [Subreddit].
/// You must be a mod of the subreddit to acess these.
class SubredditModeration {
static final _subredditRegExp = RegExp(r'{subreddit}');
final SubredditRef _subreddit;
SubredditModeration(this._subreddit);
Map<String, String> _buildOnlyMap(
SubredditModerationContentTypeFilter? only) {
final params = <String, String>{};
if (only != null) {
var _only;
if (only == SubredditModerationContentTypeFilter.submissionsOnly) {
_only = 'links';
} else {
_only = 'comments';
}
params['only'] = _only;
}
return params;
}
Stream<T> _subredditModerationListingGeneratorHelper<T>(
String api, SubredditModerationContentTypeFilter? only,
{int? limit}) =>
ListingGenerator.generator<T>(_subreddit.reddit, _formatApiPath(api),
params: _buildOnlyMap(only), limit: limit);
String _formatApiPath(String api) =>
apiPath[api].replaceAll(_subredditRegExp, _subreddit.displayName);
/// Accept an invitation to moderate the community.
Future<void> acceptInvite() async {
final url = apiPath['accept_mod_invite']
.replaceAll(_subredditRegExp, _subreddit.displayName);
return _subreddit.reddit.post(url, {});
}
/// Returns a [Stream<UserContent>] of edited [Comment]s and [Submission]s.
///
/// If `only` is provided, only [Comment]s or [Submission]s will be returned
/// exclusively.
Stream<UserContent> edited(
{SubredditModerationContentTypeFilter? only, int? limit}) =>
_subredditModerationListingGeneratorHelper('about_edited', only,
limit: limit);
/// Returns a [Stream<Message>] of moderator messages.
Stream<Message> inbox({int? limit}) =>
_subredditModerationListingGeneratorHelper('moderator_messages', null,
limit: limit);
/// Returns a [Stream<ModeratorAction>] of moderator log entries.
///
/// If `mod` is provided, only log entries for the specified moderator(s)
/// will be returned. `mod` can be a [RedditorRef], [List<RedditorRef>], or
/// a [String] of comma-separated moderator names. If `type` is provided,
/// only [ModeratorAction]s of that [ModeratorActionType] will be returned.
Stream<ModeratorAction> log(
{/* RedditorRef, List<RedditorRef>, String */ mod,
ModeratorActionType? type,
int? limit}) {
final params = <String, String>{};
if (mod != null) {
const kMods = 'mod';
if (mod is RedditorRef) {
params[kMods] = mod.displayName;
} else if (mod is List<RedditorRef>) {
params[kMods] = mod.map((r) => r.displayName).join(',');
} else if (mod is String) {
params[kMods] = mod;
} else {
throw DRAWArgumentError("Argument type 'mod' must be of "
"'RedditorRef' `List<RedditorRef>`, or `String`; got "
'${mod.runtimeType}.');
}
}
if (type != null) {
const kType = 'type';
params[kType] = moderatorActionTypesToString(type);
}
return ListingGenerator.generator(
_subreddit.reddit, _formatApiPath('about_log'),
limit: limit, params: params);
}
/// Returns a [Stream<UserContent>] of [Comment]s and [Submission]s in the
/// mod queue.
///
/// If `only` is provided, only [Comment]s or [Submission]s will be returned
/// exclusively.
Stream<UserContent> modQueue(
{SubredditModerationContentTypeFilter? only, int? limit}) =>
_subredditModerationListingGeneratorHelper('about_modqueue', only,
limit: limit);
/// Returns a [Stream<UserContent>] of [Comment]s and [Submission]s which
/// have been reported.
///
/// If `only` is provided, only [Comment]s or [Submission]s will be returned
/// exclusively.
Stream<UserContent> reports(
{SubredditModerationContentTypeFilter? only, int? limit}) =>
_subredditModerationListingGeneratorHelper('about_reports', only,
limit: limit);
/// Returns the current settings for the [Subreddit].
Future<SubredditSettings> settings() async {
final data = (await _subreddit.reddit
.get(_formatApiPath('subreddit_settings'), objectify: false))['data'];
return SubredditSettings._(_subreddit, data);
}
/// Returns a [Stream<UserContent>] of [Comment]s and [Submission]s which
/// have been marked as spam.
///
/// If `only` is provided, only [Comment]s or [Submission]s will be returned
/// exclusively.
Stream<UserContent> spam(
{SubredditModerationContentTypeFilter? only, int? limit}) =>
_subredditModerationListingGeneratorHelper('about_spam', only,
limit: limit);
/// Returns a [Stream<UserContent>] of unmoderated [Comment]s and
/// [Submission]s.
Stream<UserContent> unmoderated({int? limit}) =>
_subredditModerationListingGeneratorHelper('about_unmoderated', null,
limit: limit);
/// Returns a [Stream<Message>] of unread moderator messages.
Stream<Message> unread({int? limit}) =>
_subredditModerationListingGeneratorHelper<Message>(
'moderator_unread', null,
limit: limit);
/// Update the [Subreddit]s settings.
Future<void> update(SubredditSettings updated) async {
final data = Map<String, dynamic>.from(updated._data);
final remap = <String, String>{
'allow_top': 'default_set',
'lang': 'language',
'link_type': 'content_options',
'type': 'subreddit_type',
'sr': 'subreddit_id',
};
// Remap keys to what Reddit expects (this is dumb on their part).
remap.forEach((k, v) {
if (data[v] != null) {
data[k] = data[v];
data.remove(v);
}
});
// Not a valid key for the response.
if (data.containsKey('domain')) {
data.remove('domain');
}
// Cleanup the map before we send the request.
data.forEach((k, v) {
if (v == null) {
data[k] = 'null';
} else {
data[k] = v.toString();
}
});
data['api_type'] = 'json';
return _subreddit.reddit
.post(apiPath['site_admin'], data.cast<String, String>());
}
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/comment_forest.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'package:collection/collection.dart';
import 'comment_impl.dart';
import 'submission_impl.dart';
void setSubmission(CommentForest f, SubmissionRef s) {
f._submission = s;
}
/// A user-friendly representation of a forest of [Comment] objects.
class CommentForest {
final List _comments;
SubmissionRef _submission;
/// The number of top-level comments associated with the current
/// [CommentForest].
int get length => _comments.length;
/// A list of top-level comments associated with the current [CommentForest].
List get comments => _comments;
CommentForest(SubmissionRef submission, [List? comments])
: _comments = [],
_submission = submission {
if (comments != null) {
_comments.addAll(comments);
_comments.forEach((c) => setSubmissionInternal(c, _submission));
}
}
void _insertComment(comment) {
assert((comment is MoreComments) ||
((comment is Comment) &&
(getCommentByIdInternal(_submission, comment.fullname!) == null)));
setSubmissionInternal(comment, _submission);
assert((comment is MoreComments) ||
(getCommentByIdInternal(_submission, comment.fullname) != null));
if ((comment is MoreComments) || comment.isRoot) {
_comments.add(comment);
} else {
final parent = getCommentByIdInternal(_submission, comment.parentId)!;
parent.replies!._comments.add(comment);
}
}
void _removeMore(MoreComments more) {
final parent = getCommentByIdInternal(_submission, more.parentId);
if (parent != null) {
parent.replies!._comments.remove(more);
} else if (_submission is Submission) {
final sub = _submission as Submission;
sub.comments!._comments.removeWhere(
(comment) => ((comment is MoreComments) && (comment.id == more.id)));
}
}
dynamic operator [](int i) => _comments[i];
/// Returns a list of all [Comment]s in the [CommentForest].
///
/// The resulting [List] of [Comment] objects is built in a breadth-first
/// manner. For example, the [CommentForest]:
///
/// 1
/// + 2
/// + + 3
/// + 4
/// 5
///
/// Will return the comments in the following order: [1, 5, 2, 4, 3].
List toList() {
final comments = [];
final queue = Queue.from(_comments);
while (queue.isNotEmpty) {
final comment = queue.removeFirst();
comments.add(comment);
if ((comment is! MoreComments) && (comment.replies != null)) {
queue.addAll(comment.replies._comments);
}
}
return comments;
}
/// Iterate through the [CommentForest], expanding instances of [MoreComments].
///
/// [limit] represents the maximum number of [MoreComments] to expand
/// (default: 32), and [threshold] is the minimum number of comments that a
/// [MoreComments] object needs to represent in order to be expanded (default:
/// 0).
Future<void> replaceMore({limit = 32, threshold = 0}) async {
var remaining = limit;
final moreComments = _getMoreComments(_comments);
final skipped = [];
while (moreComments.isNotEmpty) {
final moreComment = moreComments.removeFirst();
// If we have already expanded `limit` instances of MoreComments or this
// instance's comment count is below the threshold, add the comments to
// the skipped list.
if (((remaining != null) && remaining <= 0) ||
(moreComment.count < threshold)) {
skipped.add(moreComment);
_removeMore(moreComment);
continue;
}
final newComments =
(await moreComment.comments(update: false)) as List<dynamic>;
if (remaining != null) {
--remaining;
}
// Add any additional MoreComments objects to the heap.
for (final more in _getMoreComments(newComments, _comments).toList()) {
setSubmissionInternal(more, _submission);
moreComments.add(more);
}
newComments.forEach(_insertComment);
_removeMore(moreComment);
}
}
static final dynamic _kNoParent = null;
// static final _kParentIndex = 0;
static final _kCommentIndex = 1;
static HeapPriorityQueue<MoreComments> _getMoreComments(List currentRoot,
[List? rootParent]) {
final comparator = (MoreComments a, MoreComments b) {
return a.count.compareTo(b.count);
};
final moreComments = HeapPriorityQueue<MoreComments>(comparator);
final queue = Queue<List>();
for (final rootComment in currentRoot) {
queue.add([_kNoParent, rootComment]);
}
// Keep track of which comments we've seen already.
final seen = <dynamic>{};
while (queue.isNotEmpty) {
final pair = queue.removeFirst();
// final parent = pair[_kParentIndex];
final comment = pair[_kCommentIndex];
if (comment is MoreComments) {
moreComments.add(comment);
} else if (comment.replies != null) {
for (final item in comment.replies.toList()) {
if (!seen.contains(comment)) {
queue.add([comment, item]);
seen.add(comment);
}
}
}
}
return moreComments;
}
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/user_content.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'package:draw/src/base.dart';
import 'package:draw/src/reddit.dart';
/// An abstract base class for user created content, which is one of
/// [Submission] or [Comment].
abstract class UserContent extends RedditBase {
UserContent.withPath(Reddit reddit, String infoPath)
: super.withPath(reddit, infoPath);
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/subreddit.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/image_file_reader.dart';
import 'package:draw/src/listing/listing_generator.dart';
import 'package:draw/src/listing/mixins/base.dart';
import 'package:draw/src/listing/mixins/gilded.dart';
import 'package:draw/src/listing/mixins/rising.dart';
import 'package:draw/src/listing/mixins/subreddit.dart';
import 'package:draw/src/getter_utils.dart';
import 'package:draw/src/modmail.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/util.dart';
import 'package:draw/src/models/comment.dart';
import 'package:draw/src/models/flair.dart';
import 'package:draw/src/models/mixins/messageable.dart';
import 'package:draw/src/models/multireddit.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/submission.dart';
import 'package:draw/src/models/subreddit_moderation.dart';
import 'package:draw/src/models/user_content.dart';
import 'package:draw/src/models/wikipage.dart';
enum SearchSyntax {
cloudSearch,
lucene,
plain,
}
String searchSyntaxToString(SearchSyntax s) {
switch (s) {
case SearchSyntax.cloudSearch:
return 'cloudsearch';
case SearchSyntax.lucene:
return 'lucene';
case SearchSyntax.plain:
return 'plain';
default:
throw DRAWInternalError('SearchSyntax $s is not supported');
}
}
/// A lazily initialized class representing a particular Reddit community, also
/// known as a Subreddit. Can be promoted to a [Subreddit] object.
class SubredditRef extends RedditBase
with
BaseListingMixin,
GildedListingMixin,
MessageableMixin,
RisingListingMixin,
SubredditListingMixin {
static final _subredditRegExp = RegExp(r'{subreddit}');
static String _generateInfoPath(String name) => apiPath['subreddit_about']
.replaceAll(SubredditRef._subredditRegExp, name);
Future _throwOnInvalidSubreddit(Function f,
[bool allowRedirects = true]) async {
try {
return await f();
// ignore: unused_catch_clause
} on DRAWNotFoundException catch (e) {
throw DRAWInvalidSubredditException(displayName);
// ignore: unused_catch_clause
} on DRAWRedirectResponse catch (e) {
if (allowRedirects) {
rethrow;
}
throw DRAWInvalidSubredditException(displayName);
}
}
/// Promotes this [SubredditRef] into a populated [Subreddit].
Future<Subreddit> populate() async => (await fetch()) as Subreddit;
@override
Future<dynamic> fetch() async => await _throwOnInvalidSubreddit(
() async => await reddit.get(infoPath,
params: infoParams, followRedirects: false),
false);
@override
String get displayName => _name;
late String _name;
@override
String get path => _path;
late String _path;
SubredditRelationship? _banned;
ContributorRelationship? _contributor;
SubredditFilters? _filters;
SubredditFlair? _flair;
SubredditModeration? _mod;
ModeratorRelationship? _moderator;
Modmail? _modmail;
SubredditRelationship? _muted;
SubredditQuarantine? _quarantine;
SubredditStream? _stream;
SubredditStyleSheet? _stylesheet;
SubredditWiki? _wiki;
@override
int get hashCode => _name.hashCode;
SubredditRelationship get banned {
_banned ??= SubredditRelationship(this, 'banned');
return _banned!;
}
ContributorRelationship get contributor {
_contributor ??= ContributorRelationship(this, 'contributor');
return _contributor!;
}
SubredditFilters get filters {
_filters ??= SubredditFilters._(this);
return _filters!;
}
SubredditFlair get flair {
_flair ??= SubredditFlair(this);
return _flair!;
}
SubredditModeration get mod {
_mod ??= SubredditModeration(this);
return _mod!;
}
ModeratorRelationship get moderator {
_moderator ??= ModeratorRelationship(this, 'moderator');
return _moderator!;
}
Modmail get modmail {
_modmail ??= Modmail._(this);
return _modmail!;
}
SubredditRelationship get muted {
_muted ??= SubredditRelationship(this, 'muted');
return _muted!;
}
SubredditQuarantine get quarantine {
_quarantine ??= SubredditQuarantine._(this);
return _quarantine!;
}
SubredditStream get stream {
_stream ??= SubredditStream(this);
return _stream!;
}
SubredditStyleSheet get stylesheet {
_stylesheet ??= SubredditStyleSheet(this);
return _stylesheet!;
}
SubredditWiki get wiki {
_wiki ??= SubredditWiki(this);
return _wiki!;
}
SubredditRef(Reddit reddit) : super(reddit);
/// [name] is the name of the subreddit without the 'r/' prefix.
SubredditRef.name(Reddit reddit, String name)
: _name = name,
super.withPath(reddit, _generateInfoPath(name)) {
_path =
apiPath['subreddit'].replaceAll(SubredditRef._subredditRegExp, _name);
}
@override
bool operator ==(other) {
return (other is SubredditRef) && (_name == other._name);
}
/// Returns a random submission from the [Subreddit].
Future<SubmissionRef> random() async {
try {
await _throwOnInvalidSubreddit(() async => await reddit.get(
apiPath['subreddit_random']
.replaceAll(SubredditRef._subredditRegExp, _name)));
} on DRAWRedirectResponse catch (e) {
// We expect this request to redirect to our random submission.
return SubmissionRef.withPath(reddit, e.path);
}
// ignore: only_throw_errors
throw 'This will never happen';
}
/// Return the rules for the subreddit.
Future<List<Rule>> rules() async => (await _throwOnInvalidSubreddit(
() async => await reddit.get(apiPath['rules']
.replaceAll(SubredditRef._subredditRegExp, _name))))
.cast<Rule>();
/// Returns a [Stream] of [UserContent] that match [query].
///
/// [query] is the query string to be searched for. [sort] can be one of:
/// relevance, hot, top, new, comments. [syntax] can be one of: 'cloudsearch',
/// 'lucene', 'plain'. [timeFilter] can be one of: all, day, hour, month,
/// week, year.
Stream<UserContent> search(String query,
{Sort sort = Sort.relevance,
SearchSyntax syntax = SearchSyntax.lucene,
TimeFilter timeFilter = TimeFilter.all,
Map<String, String>? params}) {
final timeStr = timeFilterToString(timeFilter);
final isNotAll = !(_name.toLowerCase() == 'all');
final data = (params != null)
? Map<String, String>.from(params)
: <String, String>{};
data['q'] = query;
data['restrict_sr'] = isNotAll.toString();
data['sort'] = sortToString(sort);
data['syntax'] = searchSyntaxToString(syntax);
data['t'] = timeStr;
return ListingGenerator.createBasicGenerator(reddit,
apiPath['search'].replaceAll(SubredditRef._subredditRegExp, _name),
params: data);
}
/// Return a [SubmissionRef] that has been stickied on the subreddit.
///
/// [number] is used to specify which stickied [Submission] to return, where 1
/// corresponds to the top sticky, 2 the second, etc.
Future<SubmissionRef> sticky({int number = 1}) async {
try {
await _throwOnInvalidSubreddit(() async => await reddit.get(
apiPath['about_sticky']
.replaceAll(SubredditRef._subredditRegExp, _name),
params: {'num': number.toString()}));
} on DRAWRedirectResponse catch (e) {
return SubmissionRef.withPath(reddit, e.path);
}
// ignore: only_throw_errors
throw 'This will never happen';
}
/// Creates a [Submission] on the [Subreddit].
///
/// [title] is the title of the submission. [selftext] is markdown formatted
/// content for a 'text' submission. Using '' will make a title-only
/// submission. [url] is the URL for a 'link' submission. [flairId] is the
/// flair template to select. If the template's 'flair_text_editable' value
/// is true, providing [flairText] will set the custom text. When [resubmit]
/// is set to false, an error will occur if the URL has already been
/// submitted. When [sendReplies] is true, messages will be sent to the
/// submission creator when comments are made on the submission.
///
/// Returns a [Submission] for the newly created submission.
Future<Submission> submit(String title,
{String? selftext,
String? url,
String? flairId,
String? flairText,
bool resubmit = true,
bool sendReplies = true,
bool nsfw = false,
bool spoiler = false}) async {
if ((selftext == null && url == null) ||
(selftext != null && url != null)) {
throw DRAWArgumentError('One of either selftext or url must be '
'provided');
}
final data = <String, String?>{
'api_type': 'json',
'sr': displayName,
'resubmit': resubmit.toString(),
'sendreplies': sendReplies.toString(),
'title': title,
'nsfw': nsfw.toString(),
'spoiler': spoiler.toString(),
};
if (flairId != null) {
data['flair_id'] = flairId;
}
if (flairText != null) {
data['flair_text'] = flairText;
}
if (selftext != null) {
data['kind'] = 'self';
data['text'] = selftext;
} else {
data['kind'] = 'link';
data['url'] = url;
}
return (await _throwOnInvalidSubreddit(
() async => await reddit.post(apiPath['submit'], data))
as Submission?)!;
}
/// Subscribes to the subreddit.
///
/// When [otherSubreddits] is provided, the provided subreddits will also be
/// subscribed to.
Future<void> subscribe({List<SubredditRef>? otherSubreddits}) async {
final data = {
'action': 'sub',
'skip_initial_defaults': 'true',
'sr_name': _subredditList(this, otherSubreddits),
};
await _throwOnInvalidSubreddit(() async =>
await reddit.post(apiPath['subscribe'], data, discardResponse: true));
}
/// Returns a dictionary of the [Subreddit]'s traffic statistics.
///
/// Raises an error when the traffic statistics aren't available to the
/// authenticated user (i.e., not a moderator of the subreddit).
Future<Map> traffic() async => (await _throwOnInvalidSubreddit(() async =>
await reddit.get(apiPath['about_traffic']
.replaceAll(SubredditRef._subredditRegExp, _name))) as Map?)!;
/// Unsubscribes from the subreddit.
///
/// When [otherSubreddits] is provided, the provided subreddits will also be
/// unsubscribed from.
Future<void> unsubscribe({List<SubredditRef>? otherSubreddits}) async {
final data = {
'action': 'unsub',
'sr_name': _subredditList(this, otherSubreddits),
};
await _throwOnInvalidSubreddit(() async =>
await reddit.post(apiPath['subscribe'], data, discardResponse: true));
}
static String _subredditList(SubredditRef subreddit,
[List<SubredditRef>? others]) {
if (others != null) {
final srs = <String>[];
srs.add(subreddit.displayName);
others.forEach((s) {
srs.add(s.displayName);
});
return srs.join(',');
}
return subreddit.displayName;
}
}
/// A class representing a particular Reddit community, also known as a
/// Subreddit.
class Subreddit extends SubredditRef with RedditBaseInitializedMixin {
/// The URL for the [Subreddit]'s header image, if it exists.
Uri? get headerImage => GetterUtils.uriOrNull(data!['header_img']);
/// The URL for the [Subreddit]'s icon, if it exists.
Uri? get iconImage => GetterUtils.uriOrNull(data!['icon_img']);
/// Whether the currently authenticated Redditor is banned from the [Subreddit].
bool? get isBanned => data!['user_is_banned'];
/// Whether the currently authenticated Redditor is an approved submitter for
/// the [Subreddit].
bool? get isContributor => data!['user_is_contributor'];
/// The URL for the [Subreddit]'s mobile header image, if it exists.
Uri? get mobileHeaderImage => GetterUtils.uriOrNull(data!['banner_img']);
/// Is the [Subreddit] restricted to users 18+.
bool get over18 => data!['over18'];
/// The title of the [Subreddit].
///
/// For example, the title of /r/drawapitesting is 'DRAW API Testing'.
String get title => data!['title'];
@override
Future<dynamic> refresh() async {
final refreshed = await populate();
setData(this, refreshed.data);
return this;
}
Subreddit.parse(Reddit reddit, Map data)
// TODO(bkonyi): fix info path not being set properly for Subreddit.
: super.name(reddit, data['data']['display_name']) {
if (!data['data'].containsKey('name')) {
// TODO(bkonyi) throw invalid object exception.
throw DRAWUnimplementedError();
}
setData(this, data['data']);
_name = data['data']['display_name'];
_path =
apiPath['subreddit'].replaceAll(SubredditRef._subredditRegExp, _name);
}
}
/// Provides functions to interact with the special [Subreddit]'s filters.
class SubredditFilters {
static final RegExp _userRegExp = RegExp(r'{user}');
static final RegExp _specialRegExp = RegExp(r'{special}');
final SubredditRef _subreddit;
SubredditFilters._(this._subreddit) {
if ((_subreddit.displayName != 'all') &&
(_subreddit.displayName != 'mod')) {
throw DRAWArgumentError(
'Only special Subreddits can be filtered (r/all or r/mod)');
}
}
/// Returns a stream of all filtered subreddits.
Stream<SubredditRef> call() async* {
final user = (await _subreddit.reddit.user.me()) as Redditor;
final path = apiPath['subreddit_filter_list']
.replaceAll(_specialRegExp, _subreddit.displayName)
.replaceAll(_userRegExp, user.displayName);
final response = (await _subreddit.reddit.get(path)) as Multireddit;
final filteredSubs = response.data!['subreddits'];
for (final sub in filteredSubs) {
yield _subreddit.reddit.subreddit(sub['name']);
}
}
/// Adds `subreddit` to the list of filtered subreddits.
///
/// Filtered subreddits will no longer be included when requesting listings
/// from `/r/all`. `subreddit` can be either an instance of [String] or
/// [SubredditRef].
Future<void> add(/* String, Subreddit */ subreddit) async {
var filteredSubreddit = '';
if (subreddit is String) {
filteredSubreddit = subreddit;
} else if (subreddit is SubredditRef) {
filteredSubreddit = subreddit.displayName;
} else {
throw DRAWArgumentError(
"Field 'subreddit' must be either a 'String' or 'SubredditRef'");
}
final user = (await _subreddit.reddit.user.me()) as Redditor;
final path = apiPath['subreddit_filter']
.replaceAll(SubredditRef._subredditRegExp, filteredSubreddit)
.replaceAll(_userRegExp, user.displayName)
.replaceAll(_specialRegExp, _subreddit.displayName);
await _subreddit.reddit
.put(path, body: {'model': '{"name" : "$filteredSubreddit"}'});
}
/// Removes `subreddit` to the list of filtered subreddits.
///
/// Filtered subreddits will no longer be included when requesting listings
/// from `/r/all`. `subreddit` can be either an instance of [String] or
/// [SubredditRef].
Future<void> remove(/* String, Subreddit */ subreddit) async {
var filteredSubreddit = '';
if (subreddit is String) {
filteredSubreddit = subreddit;
} else if (subreddit is SubredditRef) {
filteredSubreddit = subreddit.displayName;
} else {
throw DRAWArgumentError(
"Field 'subreddit' must be either a 'String' or 'SubredditRef'");
}
final user = (await _subreddit.reddit.user.me()) as Redditor;
final path = apiPath['subreddit_filter']
.replaceAll(SubredditRef._subredditRegExp, filteredSubreddit)
.replaceAll(_userRegExp, user.displayName)
.replaceAll(_specialRegExp, _subreddit.displayName);
await _subreddit.reddit.delete(path);
}
}
/// Provides a set of functions to interact with a [Subreddit]'s flair.
class SubredditFlair {
static final RegExp _kSubredditRegExp = RegExp(r'{subreddit}');
final SubredditRef _subreddit;
SubredditRedditorFlairTemplates? _templates;
SubredditLinkFlairTemplates? _linkTemplates;
SubredditFlair(this._subreddit);
SubredditRedditorFlairTemplates get templates {
_templates ??= SubredditRedditorFlairTemplates._(_subreddit);
return _templates!;
}
SubredditLinkFlairTemplates get linkTemplates {
_linkTemplates ??= SubredditLinkFlairTemplates._(_subreddit);
return _linkTemplates!;
}
Stream<Flair> call(
{/* Redditor, String */ redditor, Map<String, String>? params}) {
final data = (params != null) ? Map.from(params) : null;
if (redditor != null) {
data!['user'] = _redditorNameHelper(redditor);
}
return ListingGenerator.createBasicGenerator(
_subreddit.reddit,
apiPath['flairlist']
.replaceAll(_kSubredditRegExp, _subreddit.displayName),
params: data as Map<String, String>?);
}
/// Update the [Subreddit]'s flair configuration.
///
/// `position` specifies where flair is displayed relative to the
/// name of the Redditor. `FlairPosition.disabled` will hide flair.
///
/// `selfAssign` specifies whether or not a Redditor can set their own flair.
///
/// `linkPosition' specifies where flair is displayed relative to a
/// submission link. `FlairPosition.disabled` will hide flair for links.
///
/// 'linkSelfAssign' specifies whether or not a Redditor can set flair on
/// their links.
Future<void> configure(
{FlairPosition position = FlairPosition.right,
bool selfAssign = false,
FlairPosition linkPosition = FlairPosition.left,
bool linkSelfAssign = false}) {
final disabledPosition = (position == FlairPosition.disabled);
final disabledLinkPosition = (linkPosition == FlairPosition.disabled);
final data = <String, String>{
'api_type': 'json',
'flair_enabled': disabledPosition.toString(),
'flair_position': flairPositionToString(position),
'flair_self_assign_enabled': selfAssign.toString(),
'link_flair_position':
disabledLinkPosition ? '' : flairPositionToString(linkPosition),
'link_flair_self_assign_enabled': linkSelfAssign.toString(),
};
return _subreddit.reddit.post(
apiPath['flairtemplate']
.replaceAll(_kSubredditRegExp, _subreddit.displayName),
data);
}
/// Deletes flair for a Redditor.
///
/// `redditor` can be either a [String] representing the Redditor's name or
/// an instance of [Redditor].
Future<void> delete(/* Redditor, String */ redditor) {
final redditorName = _redditorNameHelper(redditor);
return _subreddit.reddit.post(
apiPath['deleteflair']
.replaceAll(_kSubredditRegExp, _subreddit.displayName),
<String, String>{'api_type': 'json', 'name': redditorName});
}
/// Deletes all Redditor flair in the [Subreddit].
///
/// Returns [Future<List<Map>>] containing the success or failure of each
/// delete.
Future<List<Map>> deleteAll() async {
final updates = <Flair>[];
await for (final f in call()) {
updates.add(Flair(f.user));
}
return update(updates);
}
/// Sets the flair for a [Redditor].
///
/// `redditor` can be either a [String] representing the Redditor's name or
/// an instance of [Redditor]. Must not be null.
///
/// `text` is the flair text to associate with the Redditor.
///
/// `cssClass` is the CSS class to apply to the flair.
Future<void> setFlair(/* Redditor, String */ redditor,
{String text = '', String cssClass = ''}) {
final redditorName = _redditorNameHelper(redditor);
final data = <String, String>{
'api_type': 'json',
'css_class': cssClass,
'name': redditorName,
'text': text,
};
return _subreddit.reddit.post(
apiPath['flair'].replaceAll(_kSubredditRegExp, _subreddit.displayName),
data);
}
/// Set or clear the flair of multiple Redditors at once.
///
/// `flairList` can be one of:
/// * [List<String>] of Redditor names
/// * [List<RedditorRef>]
/// * [List<Flair>]
///
/// `text` is the flair text to use when `flair_text` is missing or
/// `flairList` is not a list of mappings.
///
/// `cssClass` is the CSS class to use when `flair_css_class` is missing or
/// `flairList` is not a list of mappings.
///
/// Returns [Future<List<Map<String, String>>>] containing the success or
/// failure of each update.
Future<List<Map<String, dynamic>>> update(
/* List<String>,
List<RedditorRef>,
List<Flair> */
flairList,
{String text = '',
String cssClass = ''}) async {
if ((flairList is! List<String>) &&
(flairList is! List<RedditorRef>) &&
(flairList is! List<Flair>) ||
(flairList == null)) {
throw DRAWArgumentError('flairList must be one of List<String>,'
' List<Redditor>, or List<Map<String,String>>.');
}
var lines = <String>[];
for (final f in flairList) {
if (f is String) {
lines.add('"$f","$text","$cssClass"');
} else if (f is RedditorRef) {
lines.add('"${f.displayName}","$text","$cssClass"');
} else if (f is Flair) {
final name = f.user.displayName;
final tmpText = f.flairText ?? text;
final tmpCssClass = f.flairCssClass ?? cssClass;
lines.add('"$name","$tmpText","$tmpCssClass"');
} else {
throw DRAWInternalError('Invalid flair format');
}
}
final response = <Map<String, dynamic>>[];
final url = apiPath['flaircsv']
.replaceAll(_kSubredditRegExp, _subreddit.displayName);
while (lines.isNotEmpty) {
final batch = lines.sublist(0, min(100, lines.length));
final data = <String, String>{
'flair_csv': batch.join('\n'),
};
final List<Map<String, dynamic>> maps =
(await _subreddit.reddit.post(url, data))
.cast<Map<String, dynamic>>();
response.addAll(maps);
if (lines.length < 100) {
break;
}
lines = lines.sublist(min(lines.length - 1, 100));
}
return response;
}
}
/// Provides functions to interact with a [Subreddit]'s flair templates.
class SubredditFlairTemplates {
static final RegExp _kSubredditRegExp = RegExp(r'{subreddit}');
final SubredditRef _subreddit;
SubredditFlairTemplates._(this._subreddit);
static String _flairType(bool isLink) => isLink ? 'LINK_FLAIR' : 'USER_FLAIR';
Future<void> _add(
String text, String cssClass, bool textEditable, bool isLink) async {
final url = apiPath['flairtemplate']
.replaceAll(_kSubredditRegExp, _subreddit.displayName);
final data = <String, String>{
'api_type': 'json',
'css_class': cssClass,
'flair_type': _flairType(isLink),
'text': text,
'text_editable': textEditable.toString(),
};
await _subreddit.reddit.post(url, data);
}
Future<void> _clear(bool isLink) async {
final url = apiPath['flairtemplateclear']
.replaceAll(_kSubredditRegExp, _subreddit.displayName);
await _subreddit.reddit.post(url,
<String, String>{'api_type': 'json', 'flair_type': _flairType(isLink)});
}
Future<void> delete(String templateId) async {
final url = apiPath['flairtemplatedelete']
.replaceAll(_kSubredditRegExp, _subreddit.displayName);
await _subreddit.reddit.post(url,
<String, String>{'api_type': 'json', 'flair_template_id': templateId});
}
Future<void> update(String templateId, String text,
{String cssClass = '', bool textEditable = false}) async {
final url = apiPath['flairtemplate']
.replaceAll(_kSubredditRegExp, _subreddit.displayName);
final data = <String, String>{
'api_type': 'json',
'css_class': cssClass,
'flair_template_id': templateId,
'text': text,
'text_editable': textEditable.toString(),
};
await _subreddit.reddit.post(url, data);
}
}
/// Provides functions to interact with [Redditor] flair templates.
class SubredditRedditorFlairTemplates extends SubredditFlairTemplates {
SubredditRedditorFlairTemplates._(SubredditRef subreddit)
: super._(subreddit);
/// A [Stream] of the subreddit's Redditor flair templates.
Stream<FlairTemplate> call() async* {
final url = apiPath['flairselector'].replaceAll(
SubredditFlairTemplates._kSubredditRegExp, _subreddit.displayName);
final data = <String, String>{};
final result = (await _subreddit.reddit.post(url, data))['choices'];
for (final r in result) {
yield FlairTemplate.parse(r.cast<String, dynamic>());
}
}
/// Add a Redditor flair template to the subreddit.
///
/// `text` is the template's text, `cssClass` is the template's CSS class,
/// and `textEditable` specifies if flair text can be edited for each editor.
Future<void> add(String text,
{String cssClass = '', bool textEditable = false}) async =>
_add(text, cssClass, textEditable, false);
/// Remove all Redditor flair templates from the subreddit.
Future<void> clear() async => _clear(false);
}
/// Provides functions to interact with link flair templates.
class SubredditLinkFlairTemplates extends SubredditFlairTemplates {
SubredditLinkFlairTemplates._(SubredditRef subreddit) : super._(subreddit);
/// A [Stream] of the subreddit's link flair templates.
Stream<FlairTemplate> call() async* {
final url = apiPath['link_flair'].replaceAll(
SubredditFlairTemplates._kSubredditRegExp, _subreddit.displayName);
final result = (await _subreddit.reddit.get(url, objectify: false));
for (final r in result) {
r['flair_template_id'] = r['id'];
yield FlairTemplate.parse(r.cast<String, dynamic>());
}
}
/// Add a link flair template to the subreddit.
///
/// `text` is the template's text, `cssClass` is the template's CSS class,
/// and `textEditable` specifies if flair text can be edited for each editor.
Future<void> add(String text,
{String cssClass = '', bool textEditable = false}) async =>
_add(text, cssClass, textEditable, true);
/// Remove all link flair templates from the subreddit.
Future<void> clear() async => _clear(true);
}
/// Provides subreddit quarantine related methods.
///
/// When trying to request content from a quarantined subreddit, a
/// `DRAWAuthenticationError` is thrown if the current [User] has not opted in
/// to see content from that subreddit.
class SubredditQuarantine {
final SubredditRef _subreddit;
SubredditQuarantine._(this._subreddit);
/// Opt-in the current [User] to seeing the quarantined [Subreddit].
Future<void> optIn() async {
final data = {'sr_name': _subreddit.displayName};
await _subreddit.reddit
.post(apiPath['quarantine_opt_in'], data, discardResponse: true);
}
/// Opt-out the current [User] to seeing the quarantined [Subreddit].
///
/// When trying to request content from a quarantined subreddit, a
/// `DRAWAuthenticationError` is thrown if the current [User] has not opted in
/// to see content from that subreddit.
Future<void> optOut() async {
final data = {'sr_name': _subreddit.displayName};
await _subreddit.reddit
.post(apiPath['quarantine_opt_out'], data, discardResponse: true);
}
}
/// Represents a relationship between a [Redditor] and a [Subreddit].
class SubredditRelationship {
SubredditRef _subreddit;
final String relationship;
SubredditRelationship(this._subreddit, this.relationship);
Stream<Redditor> call(
{/* String, Redditor */ redditor, Map<String, String>? params}) {
final data = (params != null) ? Map.from(params) : <String, String>{};
if (redditor != null) {
data['user'] = _redditorNameHelper(redditor);
}
return ListingGenerator.createBasicGenerator(
_subreddit.reddit,
apiPath['list_$relationship']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName),
params: data as Map<String, String>?);
}
// TODO(bkonyi): add field for 'other settings'.
/// Add a [Redditor] to this relationship.
///
/// `redditor` can be either an instance of [Redditor] or the name of a
/// Redditor.
Future<void> add(/* String, Redditor */ redditor,
{Map<String, String>? params}) async {
final data = {
'name': _redditorNameHelper(redditor),
'type': relationship,
};
if (params != null) {
data.addAll(params);
}
await _subreddit.reddit.post(
apiPath['friend']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName),
data,
discardResponse: true);
}
/// Remove a [Redditor] from this relationship.
///
/// `redditor` can be either an instance of [Redditor] or the name of a
/// Redditor.
Future<void> remove(/* String, Redditor */ redditor,
{Map<String, String>? params}) async {
final data = {
'name': _redditorNameHelper(redditor),
'type': relationship,
};
if (params != null) {
data.addAll(params);
}
await _subreddit.reddit.post(
apiPath['unfriend']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName),
data,
discardResponse: true);
}
}
String _redditorNameHelper(/* String, RedditorRef */ redditor) {
if (redditor is RedditorRef) {
return redditor.displayName;
} else if (redditor is! String) {
throw DRAWArgumentError('Parameter redditor must be either a'
'String or Redditor');
}
return redditor;
}
/// Contains [Subreddit] traffic information for a specific time slice.
/// [uniques] is the number of unique visitors during the period, [pageviews] is
/// the total number of page views during the period, and [subscriptions] is the
/// total number of new subscriptions during the period. [subscriptions] is only
/// non-zero for time slices the length of one day. All time slices are
/// in UTC time and can be found in [periodStart], with valid slices being
/// either one hour, one day, or one month.
class SubredditTraffic {
final DateTime periodStart;
final int pageviews;
final int subscriptions;
final int uniques;
/// Build a map of [List<SubredditTraffic>] given raw traffic response from
/// the Reddit API.
///
/// This is used by the [Objector] to parse the traffic response, and may be
/// made internal at some point.
static Map<String, List<SubredditTraffic>> parseTrafficResponse(
Map response) {
return <String, List<SubredditTraffic>>{
'hour': _generateTrafficList(response['hour']),
'day': _generateTrafficList(response['day'], isDay: true),
'month': _generateTrafficList(response['month']),
};
}
static List<SubredditTraffic> _generateTrafficList(List values,
{bool isDay = false}) {
final traffic = <SubredditTraffic>[];
for (final entry in values) {
traffic.add(SubredditTraffic(entry.cast<int>()));
}
return traffic;
}
SubredditTraffic(List<int> rawTraffic, {bool isDay = false})
: pageviews = rawTraffic[2],
periodStart =
DateTime.fromMillisecondsSinceEpoch(rawTraffic[0] * 1000).toUtc(),
subscriptions = (isDay ? rawTraffic[3] : 0),
uniques = rawTraffic[1];
@override
String toString() {
return '${periodStart.toUtc()} => unique visits: $uniques, page views: $pageviews'
' subscriptions: $subscriptions';
}
}
/// Provides methods to interact with a [Subreddit]'s contributors.
///
/// Contributors are also known as approved submitters.
class ContributorRelationship extends SubredditRelationship {
ContributorRelationship(SubredditRef subreddit, String relationship)
: super(subreddit, relationship);
/// Have the current [User] remove themself from the contributors list.
Future<void> leave() async {
if (_subreddit is! Subreddit) {
_subreddit = await _subreddit.populate();
}
final data = {
'id': (_subreddit as Subreddit).fullname,
};
await _subreddit.reddit
.post(apiPath['leavecontributor'], data, discardResponse: true);
}
}
enum ModeratorPermission {
all,
access,
config,
flair,
mail,
posts,
wiki,
}
/// Provides methods to interact with a [Subreddit]'s moderators.
class ModeratorRelationship extends SubredditRelationship {
ModeratorRelationship(SubredditRef subreddit, String relationship)
: super(subreddit, relationship);
final _validPermissions = {
'access',
'config',
'flair',
'mail',
'posts',
'wiki'
};
Map<String, String> _handlePermissions(
List<ModeratorPermission> permissions) =>
<String, String>{
'permissions': permissionsString(
moderatorPermissionsToStrings(permissions), _validPermissions),
};
/// Returns a [Stream] of [Redditor]s who are moderators.
///
/// When `redditor` is provided, the resulting stream will contain at most
/// one [Redditor]. This is useful to confirm if a relationship exists, or to
/// fetch the metadata associated with a particular relationship.
@override
Stream<Redditor> call(
{/* String, RedditorRef */ redditor, Map<String, String>? params}) =>
super.call(redditor: redditor, params: params);
/// Add or invite `redditor` to be a moderator of the subreddit.
///
/// If `permissions` is not provided, the `+all` permission will be used.
/// Otherwise, `permissions` should specify the subset of permissions
/// to grant. If the empty list is provided, no permissions are granted
/// (default).
///
/// An invite will be sent unless the user making this call is an admin.
@override
Future<void> add(/* RedditorRef, String */ redditor,
{List<ModeratorPermission> permissions = const <ModeratorPermission>[],
Map<String, String>? params}) async {
final data = _handlePermissions(permissions);
if (params != null) {
data.addAll(params);
}
await super.add(
redditor,
params: data,
);
}
/// Invite `redditor` to be a moderator of this subreddit.
/// /// `redditor` is either a [RedditorRef] or username.
/// If `permissions` is not provided, the `+all` permission will be used.
/// Otherwise, `permissions` should specify the subset of permissions
/// to grant. If the empty list is provided, no permissions are granted
/// (default).
Future<void> invite(/* RedditorRef, String */ redditor,
{List<ModeratorPermission> permissions =
const <ModeratorPermission>[]}) async {
final data = <String, String>{
'name': _redditorNameHelper(redditor),
'type': 'moderator_invite',
'api_type': 'json',
};
data.addAll(_handlePermissions(permissions));
return await _subreddit.reddit.post(
apiPath['friend']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName),
data);
}
/// Remove the currently authenticated user as moderator.
Future<void> leave() async {
String fullname;
if (_subreddit is Subreddit) {
fullname = (_subreddit as Subreddit).fullname!;
} else {
fullname = (await _subreddit.populate()).fullname!;
}
await _subreddit.reddit.post(
apiPath['leavemoderator'], <String, String?>{'id': fullname},
discardResponse: true);
}
/// Remove the moderator invite for `redditor`.
///
/// `redditor` is either a [RedditorRef] or username of the user whose invite
/// is to be removed.
Future<void> removeInvite(/* RedditorRef, String */ redditor) async {
final data = <String, String>{
'name': _redditorNameHelper(redditor),
'type': 'moderator_invite',
'api_type': 'json',
};
return await _subreddit.reddit.post(
apiPath['unfriend']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName),
data,
discardResponse: true);
}
/// Updated the moderator permissions for `redditor`.
///
/// `redditor` is either a [RedditorRef] or username.
/// If `permissions` is not provided, the `+all` permission will be used.
/// Otherwise, `permissions` should specify the subset of permissions
/// to grant. If the empty list is provided, no permissions are granted
/// (default).
Future<void> update(/* RedditorRef, String */ redditor,
{List<ModeratorPermission> permissions =
const <ModeratorPermission>[]}) async {
final request = apiPath['setpermissions']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
final data = <String, String>{
'name': _redditorNameHelper(redditor),
'type': 'moderator',
};
data.addAll(_handlePermissions(permissions));
return await _subreddit.reddit.post(request, data);
}
/// Update the moderator invite for `redditor`.
///
/// `redditor` is either a [RedditorRef] or username.
/// If `permissions` is not provided, the `+all` permission will be used.
/// Otherwise, `permissions` should specify the subset of permissions
/// to grant. If the empty list is provided, no permissions are granted
/// (default).
Future<void> updateInvite(/* RedditorRef, String */ redditor,
{List<ModeratorPermission> permissions =
const <ModeratorPermission>[]}) async {
final request = apiPath['setpermissions']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
final data = <String, String>{
'name': _redditorNameHelper(redditor),
'type': 'moderator_invite',
'api_type': 'json',
};
data.addAll(_handlePermissions(permissions));
return await _subreddit.reddit.post(request, data);
}
}
enum ModmailState {
all,
archived,
highlighted,
inprogress,
mod,
newmail,
notifications,
}
String modmailStateToString(ModmailState s) {
switch (s) {
case ModmailState.all:
return 'all';
case ModmailState.archived:
return 'archived';
case ModmailState.highlighted:
return 'highlighted';
case ModmailState.inprogress:
return 'inprogress';
case ModmailState.mod:
return 'mod';
case ModmailState.newmail:
return 'new';
case ModmailState.notifications:
return 'notifications';
default:
throw DRAWInternalError('$s is not a valid ModmailSort value.');
}
}
enum ModmailSort {
mod,
recent,
unread,
user,
}
String modmailSortToString(ModmailSort s) {
switch (s) {
case ModmailSort.mod:
return 'mod';
case ModmailSort.recent:
return 'recent';
case ModmailSort.unread:
return 'unread';
case ModmailSort.user:
return 'user';
default:
throw DRAWInternalError('$s is not a valid ModmailSort value.');
}
}
/// Provides modmail functions for a [Subreddit].
class Modmail {
final SubredditRef _subreddit;
Modmail._(this._subreddit);
String _buildSubredditList(List<SubredditRef>? otherSubreddits) {
final subreddits = <SubredditRef>[_subreddit];
if (otherSubreddits != null) {
subreddits.addAll(otherSubreddits);
}
return subreddits.map((c) => c.displayName).join(',');
}
ModmailConversationRef call(String id, {bool markRead = false}) =>
ModmailConversationRef(_subreddit.reddit, id, markRead: markRead);
/// Mark the conversations for provided subreddits as read.
///
/// `otherSubreddits`: if provided, all messages in the listed subreddits
/// will also be marked as read.
///
/// `state`: can be one of all, archived, highlighted, inprogress,
/// mod, new, notifications, (default: all). "all" does not include
/// internal or archived conversations.
///
/// Returns a [List] of [ModmailConversation] instances which were marked as
/// read.
Future<List<ModmailConversationRef>> bulkRead(
{List<SubredditRef>? otherSubreddits,
ModmailState state = ModmailState.all}) async {
final params = {
'entity': _buildSubredditList(otherSubreddits),
'state': modmailStateToString(state),
};
final response = await _subreddit.reddit
.post(apiPath['modmail_bulk_read'], params, objectify: false);
final ids = response['conversation_ids'] as List;
return ids.map<ModmailConversationRef>((id) => this(id)).toList();
}
/// A [Stream] of [ModmailConversation] instances for the specified
/// subreddits.
///
/// `after`: A base36 modmail conversation id. When provided, the limiting
/// begins after this conversation.
/// `limit`: The maximum number of conversations to fetch. If not provided,
/// the server-side default is 25 at the time of writing.
/// `otherSubreddits`: A list of other subreddits for which conversations
/// should be fetched.
/// `sort`: Determines the order that the conversations will be sorted.
/// `state`:
Stream<ModmailConversation> conversations(
{String? after,
int? limit,
List<SubredditRef>? otherSubreddits,
ModmailSort sort = ModmailSort.recent,
ModmailState state = ModmailState.all}) async* {
final params = <String, String>{};
if (_subreddit.displayName != 'all') {
params['entity'] = _buildSubredditList(otherSubreddits);
}
if (after != null) {
params['after'] = after;
}
if (limit != null) {
params['limit'] = limit.toString();
}
params['sort'] = modmailSortToString(sort);
params['state'] = modmailStateToString(state);
final response = (await _subreddit.reddit
.get(apiPath['modmail_conversations'], params: params))
as Map<String, dynamic>;
final ids = (response['conversationIds'] as List).cast<String>();
for (final id in ids) {
final data = {
'conversation': response['conversations'][id],
'messages': response['messages']
};
yield ModmailConversation.parse(_subreddit.reddit, data,
convertObjects: true);
}
}
/// Create a new conversation.
///
/// `subject`: The message subject.
/// `body`: The markdown formatted body of the message.
/// `recipient`: The recipient of the conversation. Can be either a [String] or
/// a [RedditorRef].
/// `authorHidden`: When true, the author is hidden from non-moderators. This
/// is the same as replying as a subreddit.
///
/// Returns a [ModmailConversation] for the newly created conversation.
Future<ModmailConversation> create(
String subject, String body, /* String, RedditorRef */ recipient,
{authorHidden = false}) async {
final data = <String, String>{
'body': body,
'isAuthorHidden': authorHidden.toString(),
'srName': _subreddit.displayName,
'subject': subject,
'to': _redditorNameHelper(recipient),
};
return ModmailConversation.parse(
_subreddit.reddit,
(await _subreddit.reddit.post(apiPath['modmail_conversations'], data,
objectify: false)) as Map<String, dynamic>);
}
/// A [Stream] of subreddits which use the new modmail that the authenticated
/// user moderates.
Stream<SubredditRef> subreddits() async* {
final response = await _subreddit.reddit
.get(apiPath['modmail_subreddits'], objectify: false);
final subreddits =
(response['subreddits'] as Map).values.cast<Map<String, dynamic>>();
final objectified = subreddits.map<Subreddit>((s) =>
Subreddit.parse(_subreddit.reddit, {'data': snakeCaseMapKeys(s)}));
for (final s in objectified) {
yield s;
}
}
/// Return number of unread conversations by conversation state.
///
/// Note: at time of writing, only the following states are populated:
/// * archived
/// * highlighted
/// * inprogress
/// * mod
/// * newMail
/// * notifications
///
/// Returns an instance of [ModmailUnreadStatistics].
Future<ModmailUnreadStatistics> unreadCount() async {
final response = await _subreddit.reddit
.get(apiPath['modmail_unread_count'], objectify: false);
return ModmailUnreadStatistics._(response.cast<String, int>());
}
}
/// A representation of the number of unread Modmail conversations by state.
class ModmailUnreadStatistics {
final Map<String, int>? _data;
ModmailUnreadStatistics._(this._data);
int get archived => _data!['archived']!;
int get highlighted => _data!['highlighted']!;
int get inProgress => _data!['inprogress']!;
int get mod => _data!['mod']!;
int get newMail => _data!['new']!;
int get notifications => _data!['notifications']!;
@override
String toString() => JsonEncoder.withIndent(' ').convert(_data);
}
/// A wrapper class for a [Rule] of a [Subreddit].
class Rule {
bool get isLink => _isLink;
String get description => _description;
String get shortName => _shortName;
String get violationReason => _violationReason;
double get createdUtc => _createdUtc;
int get priority => _priority;
late bool _isLink;
late String _description;
late String _shortName;
late String _violationReason;
late double _createdUtc;
late int _priority;
Rule.parse(Map data) {
_isLink = (data['kind'] == 'link');
_description = data['description'];
_shortName = data['short_name'];
_violationReason = data['violation_reason'];
_createdUtc = data['created_utc'];
_priority = data['priority'];
}
@override
String toString() => '$_shortName: $_violationReason';
}
/// Provides [Comment] and [Submission] streams for the subreddit.
class SubredditStream {
final SubredditRef _subreddit;
SubredditStream(this._subreddit);
/// Yields new [Comment]s as they become available.
///
/// [Comment]s are yielded oldest first. Up to 100 historical comments will
/// initially be returned. If [limit] is provided, the stream will close
/// after [limit] iterations. If [pauseAfter] is provided, null will be
/// returned after [pauseAfter] requests without new items.
Stream<Comment?> comments({int? limit, int? pauseAfter}) =>
streamGenerator<Comment>(_subreddit.comments,
itemLimit: limit, pauseAfter: pauseAfter);
/// Yields new [Submission]s as they become available.
///
/// [Submission]s are yielded oldest first. Up to 100 historical submissions
/// will initially be returned. If [limit] is provided, the stream will close
/// after [limit] iterations. If [pauseAfter] is provided, null will be
/// returned after [pauseAfter] requests without new items.
Stream<Submission?> submissions({int? limit, int? pauseAfter}) =>
streamGenerator<Submission>(_subreddit.newest,
itemLimit: limit, pauseAfter: pauseAfter);
}
/// Represents stylesheet information for a [Subreddit].
class StyleSheet {
/// The CSS for the [Subreddit].
final String stylesheet;
/// A list of images associated with the [Subreddit].
final List<StyleSheetImage> images;
StyleSheet(this.stylesheet, [this.images = const []]);
@override
String toString() => stylesheet;
}
/// A representation of an image associated with a [Subreddit]'s [StyleSheet].
class StyleSheetImage {
/// The URL for the image.
final Uri url;
/// The CSS link for the image.
final String link;
/// The original name of the image.
final String name;
StyleSheetImage(this.url, this.link, this.name);
@override
String toString() => name;
}
enum ImageFormat {
jpeg,
png,
}
/// Provides a set of stylesheet functions to a [Subreddit].
class SubredditStyleSheet {
// static const String _kJpegHeader = '\xff\xd8\xff';
static const String _kUploadType = 'upload_type';
final SubredditRef _subreddit;
SubredditStyleSheet(this._subreddit);
/// Return the stylesheet for the [Subreddit].
Future<StyleSheet> call() async {
final uri = apiPath['about_stylesheet']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
return (await _subreddit.reddit.get(uri)) as StyleSheet;
}
Future<Uri> _uploadImage(Uri? imagePath, Uint8List? imageBytes,
ImageFormat format, Map<String, dynamic> data) async {
const kImgType = 'img_type';
if ((imagePath == null) && (imageBytes == null)) {
throw DRAWArgumentError(
'Only one of imagePath or imageBytes can be provided.');
}
if (imageBytes == null) {
final imageInfo = await loadImage(imagePath!);
// ignore: parameter_assignments
format = imageInfo['imageType'];
// ignore: parameter_assignments
imageBytes = imageInfo['imageBytes'];
}
data[kImgType] = (format == ImageFormat.png) ? 'png' : 'jpeg';
data['api_type'] = 'json';
final uri = apiPath['upload_image']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
final response = await _subreddit.reddit.post(
uri, data as Map<String, String?>?,
files: {'file': imageBytes}, objectify: false) as Map;
const kImgSrc = 'img_src';
const kErrors = 'errors';
const kErrorsValues = 'errors_values';
if (response[kImgSrc].isNotEmpty) {
return Uri.parse(response[kImgSrc]);
} else {
throw DRAWImageUploadException(
response[kErrors].first, response[kErrorsValues].first);
}
}
/// Remove the current header image for the [Subreddit].
Future<void> deleteHeader() async {
final uri = apiPath['delete_sr_header']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
await _subreddit.reddit.post(uri, {
'api_type': 'json',
});
}
/// Remove the named image from the [Subreddit].
Future<void> deleteImage(String name) async {
const kImgName = 'img_name';
final uri = apiPath['delete_sr_image']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
await _subreddit.reddit
.post(uri, <String, String>{'api_type': 'json', kImgName: name});
}
/// Remove the current mobile header image for the [Subreddit].
Future<void> deleteMobileHeader() async {
final uri = apiPath['delete_sr_banner']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
await _subreddit.reddit.post(uri, {
'api_type': 'json',
});
}
/// Remove the current mobile icon for the [Subreddit].
Future<void> deleteMobileIcon() async {
final uri = apiPath['delete_sr_icon']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
await _subreddit.reddit.post(uri, {
'api_type': 'json',
});
}
/// Update the stylesheet for the [Subreddit].
///
/// `stylesheet` is the CSS for the new stylesheet.
Future<void> update(String stylesheet, {String? reason}) async {
final uri = apiPath['subreddit_stylesheet']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
final data = <String, String?>{
'api_type': 'json',
'op': 'save',
'reason': reason,
'stylesheet_contents': stylesheet,
};
return await _subreddit.reddit.post(uri, data);
}
/// Upload an image to the [Subreddit].
///
/// `name` is the name to be used for the image. If an image already exists
/// with this name, it will be replaced.
///
/// `imagePath` is the path to a JPEG or PNG image. This path must be local
/// and accessible from disk. Will result in an [UnsupportedError] if provided
/// in a web application.
///
/// `bytes` is a list of bytes representing an image.
///
/// `format` is the format of the image defined by `bytes`.
///
/// On success, the [Uri] for the uploaded image is returned. On failure,
/// [DRAWImageUploadException] is thrown.
Future<Uri> upload(String name,
{Uri? imagePath,
Uint8List? bytes,
required ImageFormat format}) async =>
await _uploadImage(imagePath, bytes, format, <String, String>{
'name': name,
_kUploadType: 'img',
});
/// Upload an image to be used as the header image for the [Subreddit].
///
/// `imagePath` is the path to a JPEG or PNG image. This path must be local
/// and accessible from disk. Will result in an [UnsupportedError] if provided
/// in a web application.
///
/// `bytes` is a list of bytes representing an image.
///
/// `format` is the format of the image defined by `bytes`.
///
/// On success, the [Uri] for the uploaded image is returned. On failure,
/// [DRAWImageUploadException] is thrown.
Future<Uri> uploadHeader(
{Uri? imagePath,
Uint8List? bytes,
required ImageFormat format}) async =>
await _uploadImage(imagePath, bytes, format, <String, String>{
_kUploadType: 'header',
});
/// Upload an image to be used as the mobile header image for the [Subreddit].
///
/// `imagePath` is the path to a JPEG or PNG image. This path must be local
/// and accessible from disk. Will result in an [UnsupportedError] if provided
/// in a web application.
///
/// `bytes` is a list of bytes representing an image.
///
/// `format` is the format of the image defined by `bytes`.
///
/// On success, the [Uri] for the uploaded image is returned. On failure,
/// [DRAWImageUploadException] is thrown.
Future<Uri> uploadMobileHeader(
{Uri? imagePath,
Uint8List? bytes,
required ImageFormat format}) async =>
await _uploadImage(imagePath, bytes, format, <String, String>{
_kUploadType: 'banner',
});
/// Upload an image to be used as the mobile icon image for the [Subreddit].
///
/// `imagePath` is the path to a JPEG or PNG image. This path must be local
/// and accessible from disk. Will result in an [UnsupportedError] if provided
/// in a web application.
///
/// `bytes` is a list of bytes representing an image.
///
/// `format` is the format of the image defined by `bytes`.
///
/// On success, the [Uri] for the uploaded image is returned. On failure,
/// [DRAWImageUploadException] is thrown.
Future<Uri> uploadMobileIcon(
{Uri? imagePath,
Uint8List? bytes,
required ImageFormat format}) async =>
await _uploadImage(imagePath, bytes, format, <String, String>{
_kUploadType: 'icon',
});
}
/// Provides a set of wiki functions to a [Subreddit].
class SubredditWiki {
final SubredditRef _subreddit;
final SubredditRelationship banned;
final SubredditRelationship contributor;
SubredditWiki(this._subreddit)
: banned = SubredditRelationship(_subreddit, 'wikibanned'),
contributor = SubredditRelationship(_subreddit, 'wikicontributor');
/// Creates a [WikiPageRef] for the wiki page named `page`.
WikiPageRef operator [](String page) =>
WikiPageRef(_subreddit.reddit, _subreddit, page.toLowerCase());
/// Creates a new [WikiPage].
///
/// `name` is the name of the page. All spaces are replaced with '_' and the
/// name is converted to lowercase.
///
/// `content` is the initial content of the page.
///
/// `reason` is the optional message explaining why the page was created.
Future<WikiPage> create(String name, String content, {String? reason}) async {
final newName = name.replaceAll(' ', '_').toLowerCase();
final newPage = WikiPageRef(_subreddit.reddit, _subreddit, newName);
await newPage.edit(content, reason: reason);
return await newPage.populate();
}
/// A [Stream] of [WikiEdit] objects, which represent revisions made to this
/// wiki.
Stream<WikiEdit> revisions() {
final url = apiPath['wiki_revisions']
.replaceAll(SubredditRef._subredditRegExp, _subreddit.displayName);
return revisionGenerator(_subreddit, url);
}
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/comment.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
export 'comment_impl.dart' hide setSubmissionInternal, setRepliesInternal;
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/message.dart | /// Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
/// Please see the AUTHORS file for details. All rights reserved.
/// Use of this source code is governed by a BSD-style license that
/// can be found in the LICENSE file.
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/getter_utils.dart';
import 'package:draw/src/models/mixins/inboxable.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/reddit.dart';
/// A fully initialized class which represents a Message from the [Inbox].
class Message extends RedditBase
with InboxableMixin, RedditBaseInitializedMixin {
var _replies;
Message.parse(Reddit reddit, Map? data) : super(reddit) {
setData(this, data);
}
/// The author of the [Message].
String get author => data!['author'];
/// The body of the [Message].
String get body => data!['body'];
/// When was this [Message] created.
DateTime get createdUtc =>
DateTime.fromMillisecondsSinceEpoch(data!['created_utc'].round() * 1000,
isUtc: true);
/// Who is this [Message] for.
///
/// Can be for either a [Redditor] or [Subreddit].
String get destination => data!['dest'];
/// The type of distinguishment that is assigned to this message.
///
/// Can be `null` if the [Message] isn't distinguished. An example value for
/// this field is 'moderator'
String get distinguished => data!['distinguished'];
/// The [List] of replies to this [Message].
///
/// Returns and empty list if there are no replies.
List<Message> get replies {
if (_replies == null) {
_replies = <Message>[];
final repliesListing = data!['replies'];
if (repliesListing == null) {
return <Message>[];
}
final replies = repliesListing['data']['children'];
for (final reply in replies) {
_replies.add(reddit.objector.objectify(reply));
}
}
return _replies;
}
/// A [SubredditRef] representing the subreddit this message was sent to,
/// for ModMail [Message]s.
///
/// Returns `null` if this is not a ModMail [Message].
SubredditRef? get subreddit =>
GetterUtils.subredditRefOrNull(reddit, data!['subreddit']);
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/comment_impl.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/getter_utils.dart';
import 'package:draw/src/models/comment_forest.dart';
import 'package:draw/src/models/mixins/editable.dart';
import 'package:draw/src/models/mixins/gildable.dart';
import 'package:draw/src/models/mixins/inboxable.dart';
import 'package:draw/src/models/mixins/inboxtoggleable.dart';
import 'package:draw/src/models/mixins/replyable.dart';
import 'package:draw/src/models/mixins/reportable.dart';
import 'package:draw/src/models/mixins/saveable.dart';
import 'package:draw/src/models/mixins/user_content_mixin.dart';
import 'package:draw/src/models/mixins/user_content_moderation.dart';
import 'package:draw/src/models/mixins/voteable.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/submission_impl.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/models/user_content.dart';
import 'package:draw/src/reddit.dart';
import 'package:quiver/core.dart' show hash2;
// Required for `hash2`
void setSubmissionInternal(commentLike, SubmissionRef s) {
commentLike._submission = s;
// A MoreComment should never be a parent of any other comments, so don't add
// it into the Submission lookup table of id->Comment.
if (commentLike is Comment) {
insertCommentById(s, commentLike);
}
if ((commentLike is Comment) && (commentLike._replies != null)) {
for (var i = 0; i < commentLike._replies!.length; ++i) {
final comment = commentLike._replies![i];
setSubmissionInternal(comment, s);
}
}
}
void setRepliesInternal(commentLike, CommentForest comments) {
commentLike._replies = comments;
}
/// Represents comments which have been collapsed under a 'load more comments'
/// or 'continue this thread' section.
class MoreComments extends RedditBase with RedditBaseInitializedMixin {
static final RegExp _submissionRegExp = RegExp(r'{id}');
List? _comments;
final List<String> _children;
final int _count;
final String _parentId;
late SubmissionRef _submission;
List get children => _children;
/// The number of comments this instance of [MoreComments] expands into.
///
/// If `count` is 0, this instance represents a `continue this thread` link.
int get count => _count;
@override
int get hashCode => hash2(_count.hashCode, _children.hashCode);
/// True if this instance of [MoreComments] is the equivalent of the
/// 'continue this thread' link in www.reddit.com comments.
///
/// When this is true, `count` will be equal to 0.
bool get isContinueThisThread => (_count == 0);
/// True if this instance of [MoreComments] is the equivalent of the
/// 'load more comments' link in www.reddit.com comments.
///
/// When this is true, `count` should be non-zero.
bool get isLoadMoreComments => !isContinueThisThread;
/// The ID of the parent [Comment] or [Submission].
String get parentId => _parentId;
SubmissionRef get submission => _submission;
MoreComments.parse(Reddit reddit, Map data)
: _children = data['children'].cast<String>(),
_count = data['count'],
_parentId = data['parent_id'],
super(reddit) {
setData(this, data);
}
@override
bool operator ==(other) {
return ((other is MoreComments) &&
(count == other.count) &&
(children == other.children));
}
bool operator <(other) => (count > other.count);
@override
String toString() {
final buffer = StringBuffer();
buffer.write('<MoreComments count=${_children.length}, children=');
if (_children.length > 4) {
final _tmp = _children.sublist(0, 4);
_tmp.add('...');
buffer.write(_tmp);
} else {
buffer.write(_children);
}
buffer.write('>');
return buffer.toString();
}
Future<List<dynamic>?> _continueComments(bool update) async {
assert(_children.isEmpty);
final parent = (await _loadComment(_parentId.split('_')[1])) as Comment;
_comments = parent.replies?.comments;
if (update && (_comments != null)) {
_comments!.forEach((c) => setSubmissionInternal(c, submission));
}
return _comments;
}
Future<Comment?> _loadComment(String commentId) async {
if (_submission is! Submission) {
_submission = await _submission.populate();
}
final initializedSubmission = _submission as Submission;
final path = apiPath['submission'].replaceAll(
_submissionRegExp, initializedSubmission.fullname!.split('_')[1]) +
'_/' +
commentId;
final response = await reddit.get(path, params: {
'limit': initializedSubmission.data!['commentLimit'],
'sort': initializedSubmission.data!['commentSort'],
});
final comments = response[1]['listing'];
assert(comments.length == 1);
return comments[0];
}
/// Expand [MoreComments] into the list of actual [Comments] it represents.
///
/// Can contain additional [MoreComments] objects.
Future<List<dynamic>?> comments({bool update = true}) async {
if (_comments == null) {
assert(_submission is Submission);
final initializedSubmission = _submission as Submission;
if (_count == 0) {
return await _continueComments(update);
}
final data = {
'children': _children.join(','),
'link_id': initializedSubmission.fullname,
'sort': commentSortTypeToString(initializedSubmission.commentSort),
'api_type': 'json',
};
_comments =
(await reddit.post(apiPath['morechildren'], data)) as List<dynamic>?;
if (update) {
_comments!.forEach((c) {
c._submission = _submission;
});
}
}
return _fillCommentsForests(_comments!);
}
List<dynamic> _fillCommentsForests(List<dynamic> fullList) {
if (fullList.length > 1) {
final first = fullList.first;
currentIndex = 0;
return _fillCommentsForestsRecursively(fullList, first.depth);
} else {
/*
For the cases
- fullList = [MoreComments]
- fullList = [Comment]
*/
return fullList;
}
}
late int currentIndex;
List<dynamic> _fillCommentsForestsRecursively(
List<dynamic> fullList, int currentDepth) {
final commentsAtCurrentLevel = <dynamic>[fullList[currentIndex]];
currentIndex++;
while (currentIndex < fullList.length) {
final currentComment = fullList[currentIndex];
if (currentComment is Comment) {
if (currentComment.depth == currentDepth) {
commentsAtCurrentLevel.add(currentComment);
currentIndex++;
} else if (currentComment.depth < currentDepth) {
// Should be handled by previous layer, dont increment currentIndex
break;
} else {
// A new layer of children, lets add them to their parent,
// which is the last Comment added to the commentsAtCurrentLevelList
final parent = commentsAtCurrentLevel.last;
// Should be handled by next layer, dont increment currentIndex
final replies =
_fillCommentsForestsRecursively(fullList, currentDepth + 1);
parent._replies = CommentForest(submission, replies);
}
} else {
// More Comments don't have a level, but assume it is on the same level and break
commentsAtCurrentLevel.add(currentComment);
currentIndex++;
break;
}
}
return commentsAtCurrentLevel;
}
}
/// A fully initialized class which represents a single Reddit comment.
class Comment extends CommentRef
with
EditableMixin,
GildableMixin,
InboxToggleableMixin,
InboxableMixin,
RedditBaseInitializedMixin,
ReplyableMixin,
ReportableMixin,
SaveableMixin,
UserContentInitialized,
VoteableMixin {
// CommentModeration get mod; // TODO(bkonyi): implement
/// Has this [Comment] been approved.
bool get approved => data!['approved'];
/// When this [Comment] was approved.
///
/// Returns `null` if this [Comment] has not been approved.
DateTime? get approvedAtUtc =>
GetterUtils.dateTimeOrNull(data!['approved_at_utc']);
/// Which Redditor approved this [Comment].
///
/// Returns `null` if this [Comment] has not been approved.
RedditorRef? get approvedBy =>
GetterUtils.redditorRefOrNull(reddit, data!['approved_by']);
/// Is this [Comment] archived.
bool get archived => data!['archived'];
// TODO(bkonyi): update this definition.
// RedditorRef get author => reddit.redditor(data['author']);
/// The author's flair text, if set.
///
/// Returns `null` if the author does not have any flair text set.
String? get authorFlairText => data!['author_flair_text'];
/// When this [Comment] was removed.
///
/// Returns `null` if the [Comment] has not been removed.
DateTime? get bannedAtUtc =>
GetterUtils.dateTimeOrNull(data!['banned_at_utc']);
/// Which Redditor removed this [Comment].
///
/// Returns `null` if the [Comment] has not been removed.
RedditorRef? get bannedBy =>
GetterUtils.redditorRefOrNull(reddit, data!['banned_by']);
/// Is this [Comment] eligible for Reddit Gold.
bool get canGild => data!['can_gild'];
bool get canModPost => data!['can_mod_post'];
/// Is this [Comment] and its children collapsed.
bool get collapsed => data!['collapsed'];
/// The reason for this [Comment] being collapsed.
///
/// Returns `null` if the [Comment] isn't collapsed or there is no reason set.
String? get collapsedReason => data!['collapsed_reason'];
/// The time this [Comment] was created.
DateTime get createdUtc => GetterUtils.dateTimeOrNull(data!['created_utc'])!;
/// The depth of this [Comment] in the tree of comments.
int get depth => data!['depth'];
/// The number of downvotes this [Comment] has received.
int get downvotes => data!['downs'];
/// Has this [Comment] been edited.
// `edited` is `false` iff the comment hasn't been edited.
// `else edited` is a timestamp.
bool get edited => (data!['edited'] is double);
/// Ignore reports for this [Comment].
///
/// This is only visible to moderators on the [Subreddit] this [Comment] was
/// posted on.
bool? get ignoreReports => data!['ignore_reports'];
/// Did the currently authenticated [User] post this [Comment].
bool get isSubmitter => data!['is_submitter'];
/// The id of the [Submission] link.
///
/// Takes the form of `t3_7czz1q`.
String get linkId => data!['link_id'];
/// The number of reports made regarding this [Comment].
///
/// This is only visible to moderators on the [Subreddit] this [Comment] was
/// posted on.
int? get numReports => data!['num_reports'];
/// The ID of the parent [Comment] or [Submission].
String get parentId => data!['parent_id'];
String get permalink => data!['permalink'];
String? get removalReason => data!['removal_reason'];
/// Has this [Comment] been removed.
bool get removed => data!['removed'];
/// Has this [Comment] been saved.
@override
bool get saved => data!['saved'];
/// The score associated with this [Comment] (aka net-upvotes).
@override
int get score => data!['score'];
/// Is this score of this [Comment] hidden.
bool get scoreHidden => data!['score_hidden'];
/// Is this [Comment] marked as spam.
bool? get spam => data!['spam'];
/// Has this [Comment] been stickied.
bool get stickied => data!['stickied'];
/// The [Subreddit] this [Comment] was posted in.
SubredditRef get subreddit => reddit.subreddit(data!['subreddit']);
/// The id of the [Subreddit] this [Comment] was posted in.
String get subredditId => data!['subreddit_id'];
/// The type of the [Subreddit] this [Comment] was posted in.
String get subredditType => data!['subreddit_type'];
/// The number of upvotes this [Comment] has received.
int get upvotes => data!['ups'];
/// Returns true if the current [Comment] is a top-level comment. A [Comment]
/// is a top-level comment if its parent is a [Submission].
bool get isRoot {
final parentIdType = parentId.split('_')[0];
return (parentIdType == reddit.config.submissionKind);
}
/// Return the parent of the comment.
///
/// The returned parent will be an instance of either [Comment] or
/// [Submission].
Future<UserContent> parent() async {
if (_submission is! Submission) {
_submission = await _submission!.populate();
}
final initializedSubmission = _submission as Submission;
if (parentId == initializedSubmission.fullname) {
return submission;
}
// Check if the comment already exists.
CommentRef? parent = getCommentByIdInternal(_submission!, parentId);
if (parent == null) {
parent = CommentRef.withID(reddit, parentId.split('_')[1]);
parent._submission = _submission;
}
return parent;
}
String _extractSubmissionId() {
var id = data!['context'];
if (id != null) {
final split = id.split('/');
print(split);
throw DRAWUnimplementedError();
}
id = data!['link_id'];
if (id != null) {
return id.split('_')[1];
}
throw DRAWInternalError('Cannot extract submission ID from a'
' lazy-comment');
}
Comment.parse(Reddit reddit, Map data) : super.withID(reddit, data['id']) {
setData(this, data);
}
@override
Future<void> refresh() async {
if ((_submission == null) || (_submission is SubmissionRef)) {
_submission = await submission.populate();
}
final path = submission.infoPath + '_/' + _id;
final params = {
'context': '100',
};
// TODO(bkonyi): clean-up this so it's objectified in a nicer way?
final commentList = (await reddit.get(path, params: params))[1]['listing'];
final queue = Queue.from(commentList);
var comment;
while (queue.isNotEmpty && ((comment == null) || (comment._id != _id))) {
comment = queue.removeFirst();
if ((comment is CommentRef) && (comment.replies != null)) {
queue.addAll(comment.replies!.toList());
}
}
if ((comment == null) || comment._id != _id) {
throw DRAWClientError('Could not find comment with id $_id');
}
// Update the backing state of this comment object.
setData(this, comment.data);
_replies = comment.replies;
// Ensure all the sub-comments are pointing to the same submission as this.
setSubmissionInternal(this, submission);
}
/// The [Submission] which this comment belongs to.
SubmissionRef get submission {
_submission ??= reddit.submission(id: _extractSubmissionId());
return _submission!;
}
}
/// A lazily initialized class which represents a single Reddit comment. Can be
/// promoted to a [Comment].
class CommentRef extends UserContent {
CommentForest? _replies;
SubmissionRef? __submission;
final String _id;
SubmissionRef? get _submission => __submission;
set _submission(SubmissionRef? s) {
__submission = s;
if (_replies != null) {
setSubmission(_replies!, s!);
}
}
static final RegExp _commentRegExp = RegExp(r'{id}');
CommentRef.withID(Reddit reddit, this._id)
: super.withPath(reddit, _infoPath(_id));
CommentRef.withPath(Reddit reddit, url)
: _id = idFromUrl(url),
super.withPath(reddit, _infoPath(idFromUrl(url)));
static String _infoPath(String id) =>
apiPath['comment'].replaceAll(_commentRegExp, id);
// TODO(bkonyi): allow for paths without trailing '/'.
/// Retrieve a comment ID from a given URL.
///
/// Note: when [url] is a [String], it must end with a trailing '/'. This is a
/// bug and will be fixed eventually.
static String idFromUrl(/*String, Uri*/ url) {
Uri uri;
if (url is String) {
uri = Uri.parse(url);
} else if (url is Uri) {
uri = url;
} else {
throw DRAWArgumentError('idFromUrl expects either a String or Uri as'
' input');
}
final parts = uri.path.split('/');
final commentsIndex = parts.indexOf('comments');
// Check formatting of the URL.
if (commentsIndex != parts.length - 5) {
throw DRAWArgumentError("'$url' is not a valid comment url.");
}
return parts[parts.length - 2];
}
/// Promotes this [CommentRef] into a populated [Comment].
Future<Comment> populate() async {
final params = {
'id': reddit.config.commentKind + '_' + _id,
};
// Gets some general info about the comment.
final result = await reddit.get(apiPath['info'], params: params);
final List listing = result['listing'];
if (listing.isEmpty) {
throw DRAWInvalidCommentException(_id);
}
final comment = listing[0];
// The returned comment isn't fully populated, so refresh it here to
// grab replies, etc.
await comment.refresh();
return comment;
}
/// A forest of replies to the current comment.
CommentForest? get replies => _replies;
}
/// Provides a set of moderation functions for a [Comment].
class CommentModeration extends Object with UserContentModerationMixin {
@override
Comment get content => _content;
final Comment _content;
CommentModeration._(this._content);
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/inbox.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/util.dart';
import 'package:draw/src/listing/listing_generator.dart';
import 'package:draw/src/models/comment.dart';
import 'package:draw/src/models/message.dart';
/// A utility class used to interact with the Reddit inbox.
class Inbox extends RedditBase {
static final _messagesRegExp = RegExp(r'{id}');
Inbox(Reddit reddit) : super(reddit);
/// Returns a [Stream] of all inbox comments and messages.
Stream all() =>
ListingGenerator.createBasicGenerator(reddit, apiPath['inbox']);
/// Marks a list of [Comment] and/or [Message] objects as collapsed.
Future<void> collapse(List items) => _itemHelper(apiPath['collapse'], items);
/// Returns a [Stream<Comment>] of all comment replies.
Stream<Comment> commentReplies() =>
ListingGenerator.createBasicGenerator(reddit, apiPath['comment_replies']);
/// Marks a list of [Comment] and/or [Message] objects as read.
Future<void> markRead(List items) =>
_itemHelper(apiPath['read_message'], items);
/// Marks a list of [Comment] and/or [Message] objects as unread.
Future<void> markUnread(List items) =>
_itemHelper(apiPath['unread_message'], items);
Future<void> _itemHelper(String api, List items) async {
var start = 0;
var end = min(items.length, 25);
while (true) {
final sublist = items.sublist(start, end);
final nameList = <String?>[];
for (final m in sublist) {
nameList.add(await m.fullname);
}
final data = {
'id': nameList.join(','),
};
await reddit.post(api, data, discardResponse: true);
start = end;
end = min(items.length, end + 25);
if (start == end) {
break;
}
}
}
/// Returns a [Stream<Comment>] of comments in which the currently
/// authenticated user was mentioned.
///
/// A mention is a [Comment] in which the authorized user is named in the
/// form: ```/u/redditor_name```.
Stream<Comment> mentions() =>
ListingGenerator.createBasicGenerator(reddit, apiPath['mentions']);
/// Returns a [Message] associated with a given fullname.
///
/// If [messageId] is not a valid fullname for a message, null is returned.
Future<Message?> message(String messageId) async {
final listing = await reddit
.get(apiPath['message'].replaceAll(_messagesRegExp, messageId));
final messages = <Message>[];
final message = listing['listing'][0];
messages.add(message);
messages.addAll(message.replies);
for (final m in messages) {
if (m.fullname == messageId) {
return m;
}
}
return null;
}
/// Returns a [Stream<Message>] of inbox messages.
Stream<Message> messages() =>
ListingGenerator.createBasicGenerator(reddit, apiPath['messages']);
/// Returns a [Stream<Message>] of sent messages.
Stream<Message> sent() =>
ListingGenerator.createBasicGenerator(reddit, apiPath['sent']);
/// Returns a live [Stream] of [Comment] and [Message] objects.
///
/// If [pauseAfter] is provided, the [Stream] will close after [pauseAfter]
/// results are yielded. Oldest items are yielded first.
Stream stream({int? pauseAfter}) =>
streamGenerator(unread, pauseAfter: pauseAfter);
/// Returns a [Stream<Comment>] of replies to submissions made by the
/// currently authenticated user.
Stream<Comment> submissionReplies() => ListingGenerator.createBasicGenerator(
reddit, apiPath['submission_replies']);
/// Marks a list of [Comment] and/or [Message] objects as uncollapsed.
Future<void> uncollapse(List items) =>
_itemHelper(apiPath['uncollapse'], items);
/// Returns a [Stream] of [Comment] and/or [Message] objects that have not yet
/// been read.
///
/// [markRead] specifies whether or not to mark the inbox as having no new
/// messages.
Stream unread({int? limit, bool markRead = false}) {
final params = {
'mark': markRead.toString(),
};
return ListingGenerator.generator(reddit, apiPath['unread'],
params: params, limit: limit);
}
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/multireddit.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:color/color.dart';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/user.dart';
enum Visibility { hidden, private, public }
String visibilityToString(Visibility visibility) {
switch (visibility) {
case Visibility.hidden:
return 'hidden';
case Visibility.private:
return 'private';
case Visibility.public:
return 'public';
default:
throw DRAWInternalError('Visiblitity: $visibility is not supported');
}
}
enum WeightingScheme { classic, fresh }
String weightingSchemeToString(WeightingScheme weightingScheme) {
switch (weightingScheme) {
case WeightingScheme.classic:
return 'classic';
case WeightingScheme.fresh:
return 'fresh';
default:
throw DRAWInternalError(
'WeightingScheme: $weightingScheme is not supported');
}
}
enum IconName {
artAndDesign,
ask,
books,
business,
cars,
comic,
cuteAnimals,
diy,
entertainment,
foodAndDrink,
funny,
games,
grooming,
health,
lifeAdvice,
military,
modelsPinup,
music,
news,
philosophy,
picturesAndGifs,
science,
shopping,
sports,
style,
tech,
travel,
unusualStories,
video,
emptyString,
none,
}
String iconNameToString(IconName iconName) {
switch (iconName) {
case IconName.artAndDesign:
return 'art and design';
case IconName.ask:
return 'ask';
case IconName.books:
return 'books';
case IconName.business:
return 'business';
case IconName.cars:
return 'cars';
case IconName.comic:
return 'comics';
case IconName.cuteAnimals:
return 'cute animals';
case IconName.diy:
return 'diy';
case IconName.entertainment:
return 'entertainment';
case IconName.foodAndDrink:
return 'food and drink';
case IconName.funny:
return 'funny';
case IconName.games:
return 'games';
case IconName.grooming:
return 'grooming';
case IconName.health:
return 'health';
case IconName.lifeAdvice:
return 'life advice';
case IconName.military:
return 'military';
case IconName.modelsPinup:
return 'models pinup';
case IconName.music:
return 'music';
case IconName.news:
return 'news';
case IconName.philosophy:
return 'philosophy';
case IconName.picturesAndGifs:
return 'pictures and gifs';
case IconName.science:
return 'science';
case IconName.shopping:
return 'shopping';
case IconName.sports:
return 'sports';
case IconName.style:
return 'style';
case IconName.tech:
return 'tech';
case IconName.travel:
return 'travel';
case IconName.unusualStories:
return 'unusual stories';
case IconName.video:
return 'video';
case IconName.emptyString:
return '';
case IconName.none:
return 'None';
default:
throw DRAWInternalError('IconName: $iconName is not supported');
}
}
/// A class which represents a Multireddit, which is a collection of
/// [Subreddit]s.
// TODO(@ckartik): Add CommentHelper.
class Multireddit extends RedditBase with RedditBaseInitializedMixin {
static const String _kDisplayName = 'display_name';
static const String _kFrom = 'from';
// static const String _kMultiApi = 'multireddit_api';
// static const String _kMultiredditRename = 'multireddit_rename';
static const String _kMultiredditUpdate = 'multireddit_update';
// static const String _kSubreddits = 'subreddits';
static const String _kTo = 'to';
// static const String _kVisibility = 'visibility';
// static const String _kWeightingScheme = 'weighting_scheme';
static const int _redditorNameInPathIndex = 2;
static final _subredditRegExp = RegExp(r'{subreddit}');
static final RegExp _userRegExp = RegExp(r'{user}');
static final RegExp _multiredditRegExp = RegExp(r'{multi}');
// TODO(@ckartik): Try to make the data['key_color'] value null.
Color get keyColor => HexColor(data!['key_color']);
/// When was this [Multireddit] created.
DateTime get createdUtc =>
DateTime.fromMillisecondsSinceEpoch(data!['created_utc'].round() * 1000,
isUtc: true);
/// The [IconName] associated with this multireddit.
///
/// Refer to [IconName]'s Enum definition for more information.
/// If this information is not provided, will return null.
IconName? get iconName => IconName.values.firstWhereOrNull((e) =>
e.toString() == ('IconName.' + _convertToCamelCase(data!['icon_name'])!));
List<SubredditRef> get subreddits {
final subredditList = <SubredditRef>[];
subredditList.addAll(data!['subreddits'].map<SubredditRef>(
(subreddit) => SubredditRef.name(reddit, subreddit['name'])));
return subredditList;
}
/// The [Redditor] associated with this multireddit.
RedditorRef get author => _author;
late RedditorRef _author;
/// The displayName given to the [Multireddit].
String get displayName => data!['display_name'];
/// The visibility of this multireddit.
///
/// Refer to [Visibility]'s Enum definition for more information.
/// If this information is not provided, will return null.
Visibility? get visibility => Visibility.values.firstWhereOrNull(
(e) => e.toString() == ('Visibility.' + data!['visibility']));
/// The weightingScheme of this multireddit.
///
/// Refer to [WeightingScheme]'s Enum definition for more information.
/// If this information is not provided, will return null.
WeightingScheme? get weightingScheme =>
WeightingScheme.values.firstWhereOrNull((e) =>
e.toString() == ('WeightingScheme.' + data!['weighting_scheme']));
/// Does the currently authenticated [User] have the privilege to edit this
/// multireddit.
bool get canEdit => data!['can_edit'];
/// Does this multireddit require visitors to be over the age of 18.
bool get over18 => data!['over_18'];
Multireddit.parse(Reddit reddit, Map data)
: super.withPath(reddit,
_generateInfoPath(data['data']['name'], _getAuthorName(data))) {
if (!data['data'].containsKey('name')) {
throw DRAWUnimplementedError();
}
setData(this, data['data']);
_author = RedditorRef.name(reddit, _getAuthorName(data));
}
static String _getAuthorName(data) {
if (data['data']['path'] == null) {
throw DRAWInternalError('JSON data should contain value for path');
}
return data['data']['path']?.split('/')[_redditorNameInPathIndex];
}
// Returns valid info_path for multireddit with name `name`.
static String _generateInfoPath(String name, String user) =>
apiPath['multireddit']
.replaceAll(_multiredditRegExp, name)
.replaceAll(_userRegExp, user);
// Returns `str` in camel case.
static String? _convertToCamelCase(String? str) {
if (str == null) {
return null;
}
final splitStrList = str.split(RegExp(r'(\s|_)+'));
final strItr = splitStrList.iterator;
final strBuffer = StringBuffer(strItr.toString());
while (strItr.moveNext()) {
strBuffer.write(strItr.toString().substring(0, 1).toUpperCase());
strBuffer.write(strItr.toString().substring(1));
}
return strBuffer.toString();
}
/// Returns a slug version of the `title`.
static String? _sluggify(String? title) {
if (title == null) {
return null;
}
final _invalidRegExp = RegExp(r'(\s|\W|_)+');
var titleScoped = title.replaceAll(_invalidRegExp, '_').trim();
if (titleScoped.length > 21) {
titleScoped = titleScoped.substring(21);
final lastWord = titleScoped.lastIndexOf('_');
//TODO(ckartik): Test this well.
if (lastWord > 0) {
titleScoped = titleScoped.substring(lastWord);
}
}
return titleScoped;
}
/// Add a [Subreddit] to this [Multireddit].
///
/// Throws a [DRAWArgumentError] if [subreddit] is not of type [Subreddit] or [String].
///
/// `subreddit` is the name of the [Subreddit] to be added to this [Multireddit].
Future<void> add(/* String, Subreddit */ subreddit) async {
final subredditName = _subredditNameHelper(subreddit);
final newSubredditObject = {'name': '$subredditName'};
if (subreddit == null) return;
final url = apiPath[_kMultiredditUpdate]
.replaceAll(_userRegExp, _author.displayName)
.replaceAll(_multiredditRegExp, displayName)
.replaceAll(_subredditRegExp, subreddit);
await reddit.put(url, body: {'model': '{"name": "$subredditName"}'});
if (!(data!['subreddits'] as List).contains(newSubredditObject)) {
(data!['subreddits'] as List).add(newSubredditObject);
}
}
// Returns a string displayName of a subreddit.
// Throws a [DRAWArgumentError] if [subreddit] is not of type [Subreddit] or [String].
static String _subredditNameHelper(/* String, Subreddit */ subreddit) {
if (subreddit is Subreddit) {
return subreddit.displayName;
} else if (subreddit is! String) {
throw DRAWArgumentError('Parameter subreddit must be either a'
'String or Subreddit');
}
return subreddit;
}
/// Copy this [Multireddit], and return the new [Multireddit] of type [Future].
///
/// `multiName` is an optional string that will become the display name of the new
/// [Multireddit] and be used as the source for the [displayName]. If `multiName` is not
/// provided, the [name] of this [Multireddit] will be used.
Future<Multireddit> copy([String? multiName]) async {
final url = apiPath['multireddit_copy'];
final name = _sluggify(multiName) ?? data!['display_name'];
final userName = await reddit.user.me().then((me) => me!.displayName);
final scopedMultiName = multiName ?? data!['display_name'];
final jsonData = <String, String?>{
_kDisplayName: scopedMultiName,
_kFrom: infoPath,
_kTo: apiPath['multireddit']
.replaceAll(_multiredditRegExp, name)
.replaceAll(_userRegExp, userName),
};
return (await reddit.post(url, jsonData)) as Multireddit;
}
/// Delete this [Multireddit].
Future<void> delete() async =>
await reddit.delete(apiPath['multireddit_base'] + infoPath);
/*
/// Remove a [Subreddit] from this [Multireddit].
///
/// [subreddit] contains the name of the subreddit to be deleted.
Future<void> remove({String subreddit, Subreddit subredditInstance}) async {
subreddit = subredditInstance?.displayName;
if (subreddit == null) return;
final url = apiPath[_kMultiredditUpdate]
.replaceAll(_multiredditRegExp, _name)
.replaceAll(User.userRegExp, _author.displayName)
.replaceAll(_subredditRegExp, subreddit);
final data = {'model': "{'name': $subreddit}"};
await reddit.delete(url, body: data);
}
/// Rename this [Multireddit].
///
/// [newName] is the new display for this [Multireddit].
/// The [name] will be auto generated from the displayName.
Future<void> rename(newName) async {
final url = apiPath["multireddit_rename"];
final data = {
_kFrom: infoPath,
_kTo: newName,
};
final response = await reddit.post(url, data);
_name = newName;
return response;
}
/// Update this [Multireddit].
Future<void> update(
{final String displayName,
final List<String> subreddits,
final String descriptionMd,
final IconName iconName,
final Color color,
final Visibility visibility,
final WeightingScheme weightingScheme}) async {
final newSettings = {};
if (displayName != null) {
newSettings[_kDisplayName] = displayName;
}
final newSubredditList =
subreddits?.map((item) => {'name': item})?.toList();
if (newSubredditList != null) {
newSettings[_kSubreddits] = newSubredditList;
}
if (descriptionMd != null) {
newSettings["description_md"] = descriptionMd;
}
if (iconName != null) {
newSettings["icon_name"] = iconNameToString(iconName);
}
if (visibility != null) {
newSettings[_kVisibility] = visibilityToString(visibility);
}
if (weightingScheme != null) {
newSettings[_kWeightingScheme] =
weightingSchemeToString(weightingScheme);
}
if (color != null) {
newSettings["key_color"] = color.toHexColor().toString();
}
//Link to api docs: https://www.reddit.com/dev/api/#PUT_api_multi_{multipath}
final res = await reddit.put(infoPath, body: newSettings.toString());
final Multireddit newMulti = new Multireddit.parse(reddit, res['data']);
_name = newMulti.displayName;
_subreddits = newMulti._subreddits;
}
*/
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/submission.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
export 'submission_impl.dart'
hide commentSortTypeToString, getCommentByIdInternal, insertCommentById;
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/models/wikipage.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/listing/listing_generator.dart';
import 'package:draw/src/models/redditor.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/getter_utils.dart';
Stream<WikiEdit> revisionGenerator(SubredditRef s, String url) =>
WikiPageRef._revisionGenerator(s, url);
/// A lazily initialized object which represents a subreddit's wiki page. Can
/// be promoted to a populated [WikiPage].
class WikiPageRef extends RedditBase {
static final RegExp _kSubredditRegExp = RegExp(r'{subreddit}');
static final RegExp _kPageRegExp = RegExp(r'{page}');
/// The name of the wiki page.
final String name;
final String? _revision;
final SubredditRef _subreddit;
WikiPageModeration? _mod;
@override
String get infoPath => apiPath['wiki_page']
.replaceAll(_kSubredditRegExp, _subreddit.displayName)
.replaceAll(_kPageRegExp, name);
factory WikiPageRef(Reddit reddit, SubredditRef subreddit, String name,
{String? revision}) =>
WikiPageRef._(reddit, subreddit, name, revision);
WikiPageRef._(
Reddit reddit, SubredditRef subreddit, String name, String? revision)
: _subreddit = subreddit,
_revision = revision,
name = name,
super(reddit);
@override
bool operator ==(Object a) =>
((a is WikiPageRef) && (name.toLowerCase() == a.name.toLowerCase()));
@override
int get hashCode => name.toLowerCase().hashCode;
/// A helper object which allows for performing moderator actions on
/// this wiki page.
WikiPageModeration get mod {
_mod ??= WikiPageModeration._(this);
return _mod!;
}
/// Promote this [WikiPageRef] into a populated [WikiPage].
Future<WikiPage> populate() async => await fetch();
@override
Future<WikiPage> fetch() async {
final params = <String, String>{
'api_type': 'json',
};
params['page'] = name;
if (_revision != null) {
params['v'] = _revision!;
}
final result = (await reddit.get(infoPath,
params: params,
objectify: false,
followRedirects: true))['data'] as Map;
if (result.containsKey('revision_by')) {
result['revision_by'] =
Redditor.parse(reddit, result['revision_by']['data']);
}
return WikiPage._(
reddit, _subreddit, name, _revision, result as Map<String, dynamic>);
}
static Stream<WikiEdit> _revisionGenerator(
SubredditRef subreddit, String url) async* {
await for (final Map<String, dynamic> revision
in ListingGenerator.createBasicGenerator(subreddit.reddit, url)) {
if (revision.containsKey('author')) {
revision['author'] =
Redditor.parse(subreddit.reddit, revision['author']['data']);
}
revision['page'] = WikiPageRef(
subreddit.reddit, subreddit, revision['page'],
revision: revision['id']);
yield WikiEdit._(revision);
}
}
/// Edits the content of the current page.
///
/// `content` is a markdown formatted [String] which will become the new
/// content of the page.
///
/// `reason` is an optional parameter used to describe why the edit was made.
Future<void> edit(String content, {String? reason}) async {
final data = <String, String>{
'content': content,
'page': name,
};
if (reason != null) {
data['reason'] = reason;
}
return reddit.post(
apiPath['wiki_edit']
.replaceAll(_kSubredditRegExp, _subreddit.displayName),
data,
discardResponse: true);
}
/// Create a [WikiPageRef] which represents the current wiki page at the
/// provided revision.
WikiPageRef revision(String revision) =>
WikiPageRef(reddit, _subreddit, name, revision: revision);
/// A [Stream] of [WikiEdit] objects, which represent revisions made to this
/// wiki page.
Stream<WikiEdit> revisions() {
final url = apiPath['wiki_page_revisions']
.replaceAll(_kSubredditRegExp, _subreddit.displayName)
.replaceAll(_kPageRegExp, name);
return _revisionGenerator(_subreddit, url);
}
}
/// A representation of a subreddit's wiki page.
class WikiPage extends WikiPageRef with RedditBaseInitializedMixin {
WikiPage._(Reddit reddit, SubredditRef subreddit, String name,
String? revision, Map<String, dynamic> data)
: super._(reddit, subreddit, name, revision) {
setData(this, data);
}
/// The content of the page, in HTML format.
String get contentHtml => data!['content_html'];
/// The content of the page, in Markdown format.
String get contentMarkdown => data!['content_md'];
/// Whether this page may be revised.
bool get mayRevise => data!['may_revise'];
/// The date and time the revision was made.
DateTime /*!*/ get revisionDate =>
GetterUtils.dateTimeOrNull(data!['revision_date'])!;
/// The [Redditor] who made the revision.
Redditor get revisionBy => data!['revision_by'];
@override
Future<WikiPage> refresh() async {
final result = await fetch();
setData(this, result.data);
return this;
}
}
/// A representation of edits made to a [WikiPage].
class WikiEdit {
final Map<String, dynamic> data;
/// The [Redditor] who performed the edit.
Redditor get author => data['author'];
/// The [WikiPageRef] which was edited.
WikiPageRef get page => data['page'];
/// The optional reason the edit was made.
String? get reason => data['reason'];
/// The ID of the revision.
String get revision => data['id'];
/// The date and time the revision was made.
DateTime get timestamp => GetterUtils.dateTimeOrNull(data['timestamp'])!;
WikiEdit._(this.data);
@override
bool operator ==(Object other) =>
((other is WikiEdit) && (other.revision == revision));
@override
int get hashCode => revision.hashCode;
@override
String toString() => data.toString();
}
// DO NOT REORDER!
/// [WikiPage] permissions for editing and viewing.
///
/// [WikiPermissionLevel.useSubredditWikiPermissions]: use the wiki permissions
/// set by the subreddit.
///
/// [WikiPermissionLevel.approvedWikiContributors]: only approved wiki
/// contributors for a given page may edit.
///
/// [WikiPermissionlevel.modsOnly]: only moderators may edit and view this page.
enum WikiPermissionLevel {
useSubredditWikiPermissions,
approvedWikiContributors,
modsOnly,
}
/// Contains the current settings of a [WikiPageRef].
class WikiPageSettings {
Map? get data => _data;
final WikiPageRef wikiPage;
Map? _data;
final List<Redditor> _editors = <Redditor>[];
WikiPageSettings._(this.wikiPage, this._data) {
_populateEditorsList();
}
void _populateEditorsList() {
final rawEditors = data!['editors'];
for (final e in rawEditors) {
_editors.add(Redditor.parse(wikiPage.reddit, e['data']));
}
}
/// A list of [Redditor]s who are approved to edit this wiki page.
///
/// These [Redditor] objects may be partially populated. Print their `data`
/// property to see which fields are populated.
List<Redditor> get editors => _editors;
/// Whether the wiki page is listed and visible for non-moderators.
bool get listed => data!['listed'];
/// Who can edit this wiki page.
WikiPermissionLevel get permissionLevel =>
WikiPermissionLevel.values[data!['permlevel']];
/// Retrieve the most up-to-date settings and update in-place.
///
/// Returns a reference to the existing [WikiPageSettings] object.
Future<WikiPageSettings> refresh() async {
final settings = await wikiPage.mod.settings();
_data = settings.data;
_editors.clear();
_populateEditorsList();
return this;
}
@override
String toString() => data.toString();
}
// TODO(bkonyi): de-duplicate from subreddit.dart
String _redditorNameHelper(/* String, RedditorRef */ redditor) {
if (redditor is RedditorRef) {
return redditor.displayName;
} else if (redditor is! String) {
throw DRAWArgumentError('Parameter redditor must be either a'
'String or Redditor');
}
return redditor;
}
/// Provides a set of moderation functions for a [WikiPageRef].
class WikiPageModeration {
static final RegExp _kMethodRegExp = RegExp(r'{method}');
final WikiPageRef wikiPage;
WikiPageModeration._(this.wikiPage);
Future<void> _addRemoveHelper(String redditor, String method) async {
final data = <String, String>{
'page': wikiPage.name,
'username': redditor,
};
final url = apiPath['wiki_page_editor']
.replaceAll(
WikiPageRef._kSubredditRegExp, wikiPage._subreddit.displayName)
.replaceAll(_kMethodRegExp, method);
try {
await wikiPage.reddit.post(url, data, objectify: false);
// ignore: unused_catch_clause
} on DRAWNotFoundException catch (e) {
throw DRAWInvalidRedditorException(redditor);
}
}
/// Add an editor to this [WikiPageRef].
Future<void> add(/* RedditorRef, String */ redditor) async =>
_addRemoveHelper(_redditorNameHelper(redditor), 'add');
/// Remove an editor from this [WikiPageRef].
Future<void> remove(/* RedditorRef, String */ redditor) async =>
_addRemoveHelper(_redditorNameHelper(redditor), 'del');
/// The settings for this [WikiPageRef].
Future<WikiPageSettings> settings() async {
final url = apiPath['wiki_page_settings']
.replaceAll(
WikiPageRef._kSubredditRegExp, wikiPage._subreddit.displayName)
.replaceAll(WikiPageRef._kPageRegExp, wikiPage.name);
final data = (await wikiPage.reddit.get(url, objectify: false))['data'];
return WikiPageSettings._(wikiPage, data);
}
/// Updates the settings for this [WikiPageRef].
///
/// `listed` specifies whether this page appears on the page list.
/// `permissionLevel` specifies who can edit this page. See
/// [WikiPermissionLevel] for details.
///
/// Returns a new [WikiPageSettings] object with the updated settings.
Future<WikiPageSettings> update(
bool listed, WikiPermissionLevel permissionLevel) async {
final data = <String, String>{
'listed': listed.toString(),
'permlevel': permissionLevel.index.toString(),
};
final url = apiPath['wiki_page_settings']
.replaceAll(
WikiPageRef._kSubredditRegExp, wikiPage._subreddit.displayName)
.replaceAll(WikiPageRef._kPageRegExp, wikiPage.name);
final result =
(await wikiPage.reddit.post(url, data, objectify: false))['data'];
return WikiPageSettings._(wikiPage, result);
}
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/saveable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
/// Mixin for RedditBase classes that can be saved.
mixin SaveableMixin implements RedditBaseInitializedMixin {
/// Save the object.
///
/// [category] (Gold only) is the category to save the object to. If your user does not
/// have gold, this value is ignored.
Future<void> save({String? category}) async =>
reddit.post(apiPath['save'], {'category': category ?? '', 'id': fullname},
discardResponse: true);
/// Unsave the object.
Future<void> unsave() async =>
reddit.post(apiPath['unsave'], {'id': fullname}, discardResponse: true);
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/inboxable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
/// A mixin containing inbox functionality.
mixin InboxableMixin implements RedditBaseInitializedMixin {
/// Returns true if the [Inbox] item is new.
bool get newItem => data!['new'];
/// The subject of the [Inbox] item.
///
/// If this item was not retrieved via the [Inbox], this may be null.
String? get subject => data!['subject'];
/// Returns true if the current [Inbox] reply was from a [Comment].
bool get wasComment => data!['was_comment'];
/// Block the user who sent the item.
///
/// Note: Reddit does not permit blocking users unless you have a [Comment] or
/// [Message] from them in your inbox.
Future<void> block() async =>
await reddit.post(apiPath['block'], {'id': fullname});
/// Mark the item as collapsed.
///
/// This method pertains only to objects which were retrieved via the inbox.
Future<void> collapse() async => await reddit.inbox.collapse([this]);
/// Mark the item as read.
///
/// This method pertains only to objects which were retrieved via the inbox.
Future<void> markRead() async => await reddit.inbox.markRead([this]);
/// Mark the item as unread.
///
/// This method pertains only to objects which were retrieved via the inbox.
Future<void> markUnread() async => await reddit.inbox.markUnread([this]);
/// Mark the item as collapsed.
///
/// This method pertains only to objects which were retrieved via the inbox.
Future<void> uncollapse() async => await reddit.inbox.uncollapse([this]);
/// Removes the message from the recipient's view of their inbox.
Future<void> remove() async =>
await reddit.post(apiPath['del_msg'], <String, String>{'id': fullname!});
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/messageable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/reddit.dart';
import 'package:draw/src/models/subreddit.dart';
/// A mixin containing functionality to send messages to other [Redditor]s or
/// [Subreddit] moderators.
mixin MessageableMixin {
Reddit get reddit;
String get displayName;
/// Send a message.
///
/// [subject] is the subject of the message, [message] is the content of the
/// message, and [fromSubreddit] is a [Subreddit] that the message should be
/// sent from. [fromSubreddit] must be a subreddit that the current user is a
/// moderator of and has permissions to send mail on behalf of the subreddit.
// TODO(bkonyi): error handling
Future<void> message(String subject, String message,
{SubredditRef? fromSubreddit}) async {
var messagePrefix = '';
if (this is Subreddit) {
messagePrefix = '#';
}
final data = {
'subject': subject,
'text': message,
'to': messagePrefix + displayName,
'api_type': 'json',
};
if (fromSubreddit != null) {
data['from_sr'] = fromSubreddit.displayName;
}
try {
await reddit.post(apiPath['compose'], data);
} on DRAWInvalidSubredditException catch (e) {
String name;
if (e.subredditName == 'from_sr') {
name = fromSubreddit!.displayName;
} else {
name = displayName;
}
throw DRAWInvalidSubredditException(name);
// ignore: unused_catch_clause
} on DRAWInvalidRedditorException catch (e) {
throw DRAWInvalidRedditorException(displayName);
}
}
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/inboxtoggleable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
/// Interface for classes that can optionally receive inbox replies.
mixin InboxToggleableMixin implements RedditBaseInitializedMixin {
/// Disable inbox replies for the item.
Future<void> disableInboxReplies() async =>
reddit.post(apiPath['sendreplies'], {'id': fullname, 'state': 'false'},
discardResponse: true);
/// Enable inbox replies for the item.
Future<void> enableInboxReplies() async =>
reddit.post(apiPath['sendreplies'], {'id': fullname, 'state': 'true'},
discardResponse: true);
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/editable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import '../../api_paths.dart';
import '../../base_impl.dart';
import '../user_content.dart';
/// Interface for classes that can be edited and deleted.
mixin EditableMixin implements RedditBaseInitializedMixin {
/// Delete the object.
Future<void> delete() async =>
reddit.post(apiPath['del'], {'id': fullname}, discardResponse: true);
/// Replace the body of the object with [body].
///
/// [body] is the markdown formatted content for the updated object. Returns
/// the current instance of the object after updating its fields.
Future<UserContent> edit(String body) async {
final data = {'text': body, 'thing_id': fullname, 'api_type': 'json'};
// TODO(bkonyi): figure out what needs to be done here.
final updated = await reddit.post(apiPath['edit'], data);
setData(this, updated[0].data);
return this as UserContent;
}
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/replyable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/models/comment.dart';
/// A mixin for RedditBase classes that can be replied to.
mixin ReplyableMixin implements RedditBaseInitializedMixin {
// TODO(bkonyi): check if we actually need to access an array element.
/// Reply to the object.
///
/// [body] is the markdown formatted content for a comment. Returns a
/// [Comment] for the newly created comment.
Future<Comment> reply(String body) async => (await reddit.post(
apiPath['comment'],
{'text': body, 'thing_id': fullname, 'api_type': 'json'}))[0];
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/gildable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
/// Interface for classes that can be gilded.
mixin GildableMixin implements RedditBaseInitializedMixin {
/// Gild the author of the item.
Future<void> gild() async => reddit.post(
apiPath['gild_thing'].replaceAll(RegExp(r'{fullname}'), fullname), null);
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/reportable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
/// Interface for ReddieBase classes that can be reported.
mixin ReportableMixin implements RedditBaseInitializedMixin {
/// Report this object to the moderators of its [Subreddit].
///
/// [reason] is the reason for the report.
Future<void> report(String reason) async => reddit.post(
apiPath['report'], {'id': fullname, 'reason': reason, 'api_type': 'json'},
discardResponse: true);
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/voteable.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base.dart';
enum VoteState {
none,
upvoted,
downvoted,
}
int _voteStateToIndex(VoteState vote) {
switch (vote) {
case VoteState.none:
return 0;
case VoteState.upvoted:
return 1;
case VoteState.downvoted:
return -1;
}
}
/// A mixin which provides voting functionality for [Comment] and [Submission].
mixin VoteableMixin implements RedditBaseInitializedMixin {
/// The author of the item.
String get author => data!['author'];
/// The body of the item.
///
/// Returns null for non-text [Submission]s.
String? get body => data!['body'];
/// The karma score of the voteable item.
int get score => data!['score'];
/// Has the currently authenticated [User] voted on this [UserContent].
///
/// Returns [VoteState.upvoted] if the content has been upvoted,
/// [VoteState.downvoted] if it has been downvoted, and [VoteState.none]
/// otherwise.
VoteState get vote {
if (data!['likes'] == null) {
return VoteState.none;
} else if (data!['likes']) {
return VoteState.upvoted;
} else {
return VoteState.downvoted;
}
}
void _updateScore(VoteState newVote) {
if (vote == VoteState.upvoted) {
if (newVote == VoteState.downvoted) {
data!['score'] = score - 2;
} else if (newVote == VoteState.none) {
data!['score'] = score - 1;
}
} else if (vote == VoteState.none) {
if (newVote == VoteState.downvoted) {
data!['score'] = score - 1;
} else if (newVote == VoteState.upvoted) {
data!['score'] = score + 1;
}
} else if (vote == VoteState.downvoted) {
if (newVote == VoteState.upvoted) {
data!['score'] = score + 2;
} else if (newVote == VoteState.none) {
data!['score'] = score + 1;
}
}
}
Future<void> _vote(VoteState direction, bool waitForResponse) async {
if (vote == direction) {
return;
}
final response = reddit.post(
apiPath['vote'],
{
'dir': _voteStateToIndex(direction).toString(),
'id': fullname,
},
discardResponse: true);
if (waitForResponse) {
await response;
}
_updateScore(direction);
switch (direction) {
case VoteState.none:
data!['likes'] = null;
break;
case VoteState.upvoted:
data!['likes'] = true;
break;
case VoteState.downvoted:
data!['likes'] = false;
}
}
/// Clear the authenticated user's vote on the object.
///
/// Note: votes must be cast on behalf of a human user (i.e., no automatic
/// voting by bots). See Reddit rules for more details on what is considered
/// vote cheating or manipulation.
Future<void> clearVote({bool waitForResponse = true}) async =>
_vote(VoteState.none, waitForResponse);
/// Clear the authenticated user's vote on the object.
///
/// Note: votes must be cast on behalf of a human user (i.e., no automatic
/// voting by bots). See Reddit rules for more details on what is considered
/// vote cheating or manipulation.
Future<void> downvote({bool waitForResponse = true}) async =>
_vote(VoteState.downvoted, waitForResponse);
/// Clear the authenticated user's vote on the object.
///
/// Note: votes must be cast on behalf of a human user (i.e., no automatic
/// voting by bots). See Reddit rules for more details on what is considered
/// vote cheating or manipulation.
Future<void> upvote({bool waitForResponse = true}) async =>
_vote(VoteState.upvoted, waitForResponse);
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/user_content_moderation.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/api_paths.dart';
import 'package:draw/src/base_impl.dart';
import 'package:draw/src/exceptions.dart';
import 'package:draw/src/models/comment.dart';
enum DistinctionType {
yes,
no,
admin,
special,
}
String distinctionTypeToString(DistinctionType type) {
switch (type) {
case DistinctionType.yes:
return 'yes';
case DistinctionType.no:
return 'no';
case DistinctionType.admin:
return 'admin';
case DistinctionType.special:
return 'special';
default:
throw DRAWInternalError('Invalid user content distinction type: $type.');
}
}
/// Provides moderation methods for [Comment]s and [Submission]s.
mixin UserContentModerationMixin {
RedditBaseInitializedMixin get content;
/// Approve a [Comment] or [Submission].
///
/// Approving a comment or submission reverts removal, resets the report
/// counter, adds a green check mark which is visible to other moderators
/// on the site, and sets the `approvedBy` property to the authenticated
/// user.
Future<void> approve() async => content.reddit.post(
apiPath['approve'], <String, String>{'id': content.fullname!},
discardResponse: true);
/// Distinguish a [Comment] or [Submission].
///
/// `how` is a [DistinctionType] value, where `yes` distinguishes the content
/// as a moderator, and `no` removes distinction. `admin` and `special`
/// require special privileges.
///
/// If `sticky` is `true` and the comment is top-level, the [Comment] will be
/// placed at the top of the comment thread. If the item to be distinguished
/// is not a [Comment] or is not a top-level [Comment], this parameter is
/// ignored.
Future<void> distinguish(
{required DistinctionType how, bool sticky = false}) async {
final data = <String, String>{
'how': distinctionTypeToString(how),
'id': content.fullname!,
'api_type': 'json'
};
if (sticky && (content is Comment) && (content as Comment).isRoot) {
data['sticky'] = 'true';
}
return content.reddit.post(apiPath['distinguish'], data);
}
/// Ignore Future<void> reports on a [Comment] or [Submission].
///
/// Prevents Future<void> reports on this [Comment] or [Submission] from triggering
/// notifications and appearing in the mod queue. The report count will
/// continue to increment.
Future<void> ignoreReports() async => content.reddit.post(
apiPath['ignore_reports'], <String, String>{'id': content.fullname!},
discardResponse: true);
/// Remove a [Comment] or [Submission].
///
/// Set `spam` to `true` to help train the subreddit's spam filter.
Future<void> remove({bool spam = false}) async => content.reddit.post(
apiPath['remove'],
<String, String>{'id': content.fullname!, 'spam': spam.toString()},
discardResponse: true);
/// Remove distinguishing on a [Comment] or [Submission].
Future<void> undistinguish() async => distinguish(how: DistinctionType.no);
/// Resume receiving Future<void> reports for a [Comment] or [Submission].
///
/// Future<void> reports will trigger notifications and appear in the mod queue.
Future<void> unignoreReports() async => content.reddit.post(
apiPath['unignore_reports'], <String, String>{'id': content.fullname!},
discardResponse: true);
}
| 0 |
mirrored_repositories/DRAW/lib/src/models | mirrored_repositories/DRAW/lib/src/models/mixins/user_content_mixin.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'package:draw/src/base_impl.dart';
mixin UserContentInitialized implements RedditBaseInitializedMixin {
/// The amount of silver gilded to this [UserContent].
int get silver => data!['gildings']['gid_1'];
/// The amount of gold gilded to this [UserContent].
int get gold => data!['gildings']['gid_2'];
/// The amount of platinum gilded to this [UserContent].
int get platinum => data!['gildings']['gid_3'];
/// A [List] of reports made by moderators.
///
/// Each report consists of a list with two entries. The first entry is the
/// name of the moderator who submitted the report. The second is the report
/// reason.
List<List<String>> get modReports {
final reports = data!['mod_reports'] as List;
return reports.map<List<String>>((e) => e.cast<String>()).toList();
}
/// A [List] of reports made by users.
///
/// Each report consists of a list with two entries. The first entry is the
/// report reason. The second is the number of times this reason has been
/// reported.
List<List<dynamic>> get userReports =>
(data!['user_reports'] as List).cast<List<dynamic>>();
/// True if the currently authenticated user has marked this content as saved.
bool get saved => data!['saved'];
}
| 0 |
mirrored_repositories/DRAW/lib/src | mirrored_repositories/DRAW/lib/src/listing/listing_generator.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/reddit.dart';
/// An abstract static class used to generate [Stream]s of [RedditBase] objects.
/// This class should not be used directly, as it is used by various methods
/// defined in children of [RedditBase].
abstract class ListingGenerator {
static const defaultRequestLimit = 100;
static int? getLimit(Map<String, String>? params) {
if ((params != null) && params.containsKey('limit')) {
return int.tryParse(params['limit']!);
}
return null;
}
static Stream<T> createBasicGenerator<T>(
final Reddit reddit, final String path,
{int? limit,
String? after,
Map<String, String>? params,
bool objectify = true}) =>
generator<T>(reddit, path,
limit: limit ?? getLimit(params),
after: after,
params: params,
objectify: objectify);
/// An asynchronous iterator method used to make Reddit API calls as defined
/// by [api] in blocks of size [limit]. The default [limit] is specified by
/// [defaultRequestLimit]. [after] specifies which fullname should be used as
/// an anchor point for the slice. Returns a [Stream<T>] which can be iterated
/// over using an asynchronous for-loop.
static Stream<T> generator<T>(final Reddit reddit, final String api,
{int? limit,
String? after,
Map<String, String>? params,
bool objectify = true}) async* {
final kLimitKey = 'limit';
final kAfterKey = 'after';
final nullLimit = 100;
final Map<String, String?> paramsInternal = (params == null)
? <String, String>{}
: Map<String, String>.from(params);
final _limit = limit;
paramsInternal[kLimitKey] = (_limit ?? nullLimit).toString();
// If after is provided, we'll start getting objects older than the object
// ID specified.
if (after != null) {
paramsInternal[kAfterKey] = after;
}
var yielded = 0;
var index = 0;
List<T>? listing;
var exhausted = false;
Future<List?> _nextBatch() async {
if (exhausted) {
return null;
}
var response =
await reddit.get(api, params: paramsInternal, objectify: objectify);
var newListing;
if (response is List) {
newListing = response;
exhausted = true;
} else {
response = response as Map?;
newListing = response!['listing'].cast<T>();
if (response[kAfterKey] == null) {
exhausted = true;
} else {
paramsInternal[kAfterKey] = response[kAfterKey];
}
}
if (newListing.length == 0) {
return null;
}
index = 0;
return newListing;
}
while ((_limit == null) || (yielded < _limit)) {
if ((listing == null) || (index >= listing.length)) {
listing = (await _nextBatch())?.cast<T>();
if (listing == null) {
break;
}
}
yield listing[index];
++index;
++yielded;
}
}
}
| 0 |
mirrored_repositories/DRAW/lib/src/listing | mirrored_repositories/DRAW/lib/src/listing/mixins/rising.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import '../listing_generator.dart';
import '../../reddit.dart';
import '../../models/user_content.dart';
mixin RisingListingMixin {
Reddit get reddit;
String get path;
/// Returns a random [UserContent] that is "rising".
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
Stream<UserContent> randomRising(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, path + 'randomrising',
limit: limit, after: after, params: params);
/// Returns a [UserContent] that is "rising".
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
Stream<UserContent> rising(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, path + 'rising',
limit: limit, after: after, params: params);
}
| 0 |
mirrored_repositories/DRAW/lib/src/listing | mirrored_repositories/DRAW/lib/src/listing/mixins/redditor.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import '../../models/user_content.dart';
import '../../reddit.dart';
import '../listing_generator.dart';
import 'base.dart';
/// A mixin which provides the ability to get [Redditor] related streams.
mixin RedditorListingMixin {
Reddit get reddit;
String get path;
SubListing? _comments;
SubListing? _submissions;
/// Provides an instance of [SubListing], used to make requests for
/// [Comment]s.
SubListing get comments {
_comments ??= SubListing(reddit, path, 'comments/');
return _comments!;
}
/// Provides an instance of [SubListing], used to make requests for
/// [Submission]s.
SubListing get submissions {
_submissions ??= SubListing(reddit, path, 'submitted/');
return _submissions!;
}
/// Returns a [Stream] of content that the user has downvoted.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
///
/// May raise an exception on access if the current user is not authorized to
/// access this list.
Stream<UserContent> downvoted(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, path + 'downvoted',
limit: limit, after: after, params: params);
/// Returns a [Stream] of content that the user has gilded.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
///
/// May raise an exception on access if the current user is not authorized to
/// access this list.
Stream<UserContent> gildings(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, path + 'gilded/given',
limit: limit, after: after, params: params);
/// Returns a [Stream] of content that the user has hidden.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
///
/// May raise an exception on access if the current user is not authorized to
/// access this list.
Stream<UserContent> hidden(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, path + 'hidden',
limit: limit, after: after, params: params);
/// Returns a [Stream] of content that the user has saved.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
///
/// May raise an exception on access if the current user is not authorized to
/// access this list.
Stream<UserContent> saved(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, path + 'saved',
limit: limit, after: after, params: params);
/// Returns a [Stream] of content that the user has upvoted.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
///
/// May raise an exception on access if the current user is not authorized to
/// access this list.
Stream<UserContent> upvoted(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator(reddit, path + 'upvoted',
limit: limit, after: after, params: params);
}
class SubListing extends Object with BaseListingMixin {
@override
final Reddit reddit;
late String _path;
@override
String get path => _path;
SubListing(this.reddit, final String path, final String api) {
_path = path + api;
}
}
| 0 |
mirrored_repositories/DRAW/lib/src/listing | mirrored_repositories/DRAW/lib/src/listing/mixins/gilded.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/src/listing/listing_generator.dart';
import 'package:draw/src/models/mixins/user_content_mixin.dart';
import 'package:draw/src/reddit.dart';
/// A mixin which contains the functionality required to get a [Stream] of
/// gilded content.
mixin GildedListingMixin {
Reddit get reddit;
String get path;
/// Returns a [Stream] of content that has been gilded.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
Stream<UserContentInitialized> gilded(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.createBasicGenerator<UserContentInitialized>(
reddit, path + 'gilded',
limit: limit, after: after, params: params);
}
| 0 |
mirrored_repositories/DRAW/lib/src/listing | mirrored_repositories/DRAW/lib/src/listing/mixins/base.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import '../../exceptions.dart';
import '../../reddit.dart';
import '../../models/user_content.dart';
import '../../models/redditor.dart';
import '../listing_generator.dart';
import 'redditor.dart';
/// An enum used to specify how to filter results based on time.
enum TimeFilter {
all,
day,
hour,
month,
week,
year,
}
/// Converts a [TimeFilter] into a simple [String].
String timeFilterToString(TimeFilter filter) {
switch (filter) {
case TimeFilter.all:
return 'all';
case TimeFilter.day:
return 'day';
case TimeFilter.hour:
return 'hour';
case TimeFilter.month:
return 'month';
case TimeFilter.week:
return 'week';
case TimeFilter.year:
return 'year';
default:
throw DRAWInternalError('TimeFilter $filter is not'
'supported');
}
}
/// An enum used to specify how to sort results.
enum Sort {
relevance,
hot,
top,
newest,
comments,
}
/// Converts a [Sort] into a simple [String].
String sortToString(Sort sort) {
switch (sort) {
case Sort.relevance:
return 'relevance';
case Sort.hot:
return 'hot';
case Sort.top:
return 'top';
case Sort.newest:
return 'new';
case Sort.comments:
return 'comments';
default:
throw DRAWInternalError('Sort $sort is not supported');
}
}
/// A mixin with common listing functionality, including [ListingGenerator]
/// creation and standard listing requests by [Sort] type.
mixin BaseListingMixin {
Reddit get reddit;
String get path;
Stream<UserContent> _buildGenerator(
int? limit, String? after, Map<String, String>? params, String sort) {
var _params = params;
if ((this is RedditorRef) || (this is SubListing)) {
var arg = '';
if (this is RedditorRef) {
arg = 'overview';
}
_params ??= <String, String>{};
_params['sort'] = sort;
return ListingGenerator.generator<UserContent>(reddit, path + arg,
limit: limit ?? ListingGenerator.getLimit(params),
after: after,
params: _params);
}
return ListingGenerator.generator<UserContent>(reddit, path + sort,
limit: limit ?? ListingGenerator.getLimit(_params),
after: after,
params: _params);
}
Stream<UserContent> _buildTimeFilterGenerator(int? limit, String? after,
Map<String, String>? params, String sort, TimeFilter timeFilter) {
final _params = params ?? {};
_params['t'] = timeFilterToString(timeFilter);
return _buildGenerator(limit, after, _params, sort);
}
/// Returns a [Stream] of controversial comments and submissions. [timeFilter]
/// is used to filter comments and submissions by time period.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
Stream<UserContent> controversial(
{TimeFilter timeFilter = TimeFilter.all,
int? limit,
String? after,
Map<String, String>? params}) =>
_buildTimeFilterGenerator(
limit, after, params, 'controversial', timeFilter);
/// Returns a [Stream] of hot comments and submissions.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
Stream<UserContent> hot(
{int? limit, String? after, Map<String, String>? params}) =>
_buildGenerator(limit, after, params, 'hot');
/// Returns a [Stream] of the newest comments and submissions.
///
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
Stream<UserContent> newest(
{int? limit, String? after, Map<String, String>? params}) =>
_buildGenerator(limit, after, params, 'new');
/// Returns a [Stream] of the top comments and submissions.
///
/// [timeFilter] is used to filter comments and submissions by time period.
/// `limit` is the maximum number of objects returned by Reddit per request
/// (the default is 100). If provided, `after` specifies from which point
/// Reddit will return objects of the requested type. `params` is a set of
/// additional parameters that will be forwarded along with the request.
Stream<UserContent> top(
{TimeFilter timeFilter = TimeFilter.all,
int? limit,
String? after,
Map<String, String>? params}) =>
_buildTimeFilterGenerator(limit, after, params, 'top', timeFilter);
}
| 0 |
mirrored_repositories/DRAW/lib/src/listing | mirrored_repositories/DRAW/lib/src/listing/mixins/subreddit.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import '../listing_generator.dart';
import '../../base.dart';
import '../../models/comment.dart';
import '../../models/subreddit.dart';
import '../../reddit.dart';
import 'gilded.dart';
mixin SubredditListingMixin {
Reddit get reddit;
String get path;
CommentHelper? _commentHelper;
CommentHelper get comments {
_commentHelper ??= CommentHelper(this as SubredditRef);
return _commentHelper!;
}
}
class CommentHelper extends RedditBase with GildedListingMixin {
@override
String get path => _subreddit.path;
final SubredditRef _subreddit;
CommentHelper(this._subreddit) : super(_subreddit.reddit);
// TODO(bkonyi): document.
Stream<Comment> call(
{int? limit, String? after, Map<String, String>? params}) =>
ListingGenerator.generator<Comment>(reddit, _path(),
limit: limit ?? ListingGenerator.getLimit(params),
after: after,
params: params);
String _path() => _subreddit.path + 'comments/';
}
| 0 |
mirrored_repositories/DRAW | mirrored_repositories/DRAW/test/test_authenticator.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:collection/collection.dart';
import 'package:oauth2/oauth2.dart' as oauth2;
// ignore: import_of_legacy_library_into_null_safe
import 'package:reply/reply.dart';
import 'package:draw/src/auth.dart';
import 'package:draw/src/draw_config_context.dart';
import 'package:draw/src/exceptions.dart';
const redirectResponseStr = 'DRAWRedirectResponse';
const notFoundExceptionStr = 'DRAWNotFoundException';
/// A drop-in replacement for [Authenticator], used for recording and replaying
/// Reddit API interactions, used primarily for testing.
class TestAuthenticator extends Authenticator {
final String _recordingPath;
final Authenticator? _recordAuth;
final _recorder = Recorder<List, dynamic>();
bool get isRecording => (_recordAuth == null);
late Recording _recording;
/// Creates a [TestAuthenticator] object which either reads a recording from
/// [recordingPath] or records Reddit API requests and responses if
/// [recordAuth] is provided. If [recordAuth] is provided, it must be a
/// valid Authenticator with valid OAuth2 credentials that is capable of
/// making requests to the Reddit API. Note: when recording Reddit API
/// interactions, [writeRecording] must be called to write all prior records
/// to the file at [recordingPath].
TestAuthenticator(String recordingPath, {Authenticator? recordAuth})
: _recordingPath = recordingPath,
_recordAuth = recordAuth,
super(DRAWConfigContext(),
oauth2.AuthorizationCodeGrant('', Uri(), Uri())) {
if (isRecording) {
final rawRecording = File(recordingPath).readAsStringSync();
final recording = json.decode(rawRecording).cast<Map<String, dynamic>>();
_recording = Recording.fromJson(recording,
toRequest: (q) => q,
toResponse: (r) => r,
requestEquality: const ListEquality());
}
}
@override
Future refresh() async {
if (isRecording) {
throw DRAWAuthenticationError('cannot refresh a TestAuthenticator.');
}
return _recordAuth!.refresh();
}
@override
Future revoke() async {
if (isRecording) {
throw DRAWAuthenticationError('cannot revoke a TestAuthenticator.');
}
return _recordAuth!.revoke();
}
dynamic _copyResponse(response) {
if (response == null) {
return '';
}
// This is a way to do a recursive deep-copy of the response so we don't
// accidentally overwrite data in the tests.
return json.decode(json.encode(response));
}
void _throwOnError(dynamic result) {
if ((result is List) && result.isNotEmpty) {
final type = result[0];
if (type is String) {
switch (type) {
case redirectResponseStr:
throw DRAWRedirectResponse(result[1], null);
case notFoundExceptionStr:
throw DRAWNotFoundException(result[1], result[2]);
default:
throw DRAWInternalError(
'Could not determine exception type: $type');
}
}
}
}
void _recordException(Uri path, params, Exception e) {
if (e is DRAWRedirectResponse) {
_recorder.given([path.toString(), params.toString()]).reply(
[redirectResponseStr, e.path]).once();
} else if (e is DRAWNotFoundException) {
_recorder.given([path.toString(), params.toString()]).reply(
[notFoundExceptionStr, e.reason, e.message]).once();
} else {
throw DRAWInternalError('Unexpected exception type');
}
throw e;
}
@override
Future<dynamic> get(Uri path,
{Map<String, String?>? params, bool followRedirects = false}) async {
var result;
if (isRecording) {
result = _recording.reply([path.toString(), params.toString()]);
_throwOnError(result);
} else {
try {
result = await _recordAuth!
.get(path, params: params, followRedirects: followRedirects);
} catch (e) {
// Throws.
_recordException(path, params, e as Exception);
}
_recorder
.given([path.toString(), params.toString()])
.reply(_copyResponse(result))
.once();
}
return result;
}
@override
Future<dynamic> post(Uri path, Map<String, String?>? body,
{Map<String, Uint8List?>? files, Map? params}) async {
var result;
if (isRecording) {
// Note: we ignore the files parameter for creating recordings, so tests
// which try to overwrite a remote file multiple times might have issues.
result = _recording.reply([path.toString(), body.toString()]);
_throwOnError(result);
} else {
try {
result =
await _recordAuth!.post(path, body, files: files, params: params);
} catch (e) {
// Throws.
_recordException(path, body, e as Exception);
}
_recorder
.given([path.toString(), body.toString()])
.reply(_copyResponse(result))
.once();
}
return (result == '') ? null : result;
}
@override
Future<dynamic> put(Uri path, {Map<String, String>? body}) async {
var result;
if (isRecording) {
result = _recording.reply([path.toString(), body.toString()]);
_throwOnError(result);
} else {
try {
result = await _recordAuth!.put(path, body: body);
} catch (e) {
// Throws.
_recordException(path, body, e as Exception);
}
_recorder
.given([path.toString(), body.toString()])
.reply(_copyResponse(result))
.once();
}
return result;
}
@override
Future<dynamic> delete(Uri path, {Map<String, String>? body}) async {
var result;
if (isRecording) {
result = _recording.reply([path.toString(), body.toString()]);
_throwOnError(result);
} else {
try {
result = await _recordAuth!.delete(path, body: body);
} catch (e) {
// Throws.
_recordException(path, body, e as Exception);
}
_recorder
.given([path.toString(), body.toString()])
.reply(_copyResponse(result) ?? '')
.once();
}
return (result == '') ? null : result;
}
@override
bool get isValid {
return _recordAuth?.isValid ?? true;
}
/// Writes the recorded Reddit API requests and their corresponding responses
/// to [recordingPath] and returns a [Future<File>], which is the file that
/// has been written to, when in recording mode. When not in recording mode,
/// does nothing and returns null.
Future<File>? writeRecording() {
if (!isRecording) {
return (File(_recordingPath)).writeAsString(json
.encode(_recorder.toRecording().toJsonEncodable(
encodeRequest: (q) => q, encodeResponse: (r) => r))
.toString());
}
return null;
}
}
| 0 |
mirrored_repositories/DRAW | mirrored_repositories/DRAW/test/test_utils.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'auth/credentials.dart';
import 'test_authenticator.dart';
Future<Reddit> createRedditTestInstance(String path,
{bool live = false}) async {
var testAuth;
if (live) {
final tempReddit = await Reddit.createScriptInstance(
userAgent: 'foobar',
username: kUsername,
password: kPassword,
clientId: kScriptClientID,
clientSecret: kScriptClientSecret);
testAuth = TestAuthenticator(path, recordAuth: tempReddit.auth);
} else {
testAuth = TestAuthenticator(path);
}
return Reddit.fromAuthenticator(testAuth);
}
Future<void> writeRecording(Reddit reddit) async {
assert(reddit.auth is TestAuthenticator);
final auth = reddit.auth as TestAuthenticator;
await auth.writeRecording();
}
| 0 |
mirrored_repositories/DRAW | mirrored_repositories/DRAW/test/test_all.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'auth/run_live_auth_tests.dart' as live_auth_test;
import 'comment/comment_test.dart' as comment_test;
import 'frontpage/frontpage_test.dart' as frontpage_test;
import 'gilded_listing_mixin/gilded_listing_mixin_test.dart'
as gilded_listing_mixin_test;
import 'inbox/inbox_test.dart' as inbox_test;
import 'messageable_mixin/messageable_mixin_test.dart'
as messageable_mixin_test;
import 'multireddit/multireddit_test.dart' as multireddit_test;
import 'redditor/redditor_test.dart' as redditor_test;
import 'rising_listing_mixin/rising_listing_mixin_test.dart'
as rising_listing_mixin_test;
import 'submission/submission_test.dart' as submission_test;
import 'subreddit/subreddit_listing_mixin_test.dart'
as subreddit_listing_mixin_test;
import 'subreddit/subreddit_moderation_test.dart' as subreddit_mod_test;
import 'subreddit/subreddits_test.dart' as subreddits_test;
import 'subreddit/subreddit_test.dart' as subreddit_test;
import 'unit_tests/enum_stringify_test.dart' as enum_stringify_test;
import 'unit_tests/test_draw_config_context.dart' as draw_config_test;
import 'unit_tests/utils_test.dart' as utils_test;
import 'user_content_moderation/user_content_moderation_test.dart'
as user_content_moderation_test;
import 'user_content/user_content_test.dart' as user_content_test;
import 'user/user_test.dart' as user_test;
void main() {
live_auth_test.main();
comment_test.main();
draw_config_test.main();
enum_stringify_test.main();
frontpage_test.main();
gilded_listing_mixin_test.main();
inbox_test.main();
messageable_mixin_test.main();
multireddit_test.main();
redditor_test.main();
rising_listing_mixin_test.main();
submission_test.main();
subreddits_test.main();
subreddit_listing_mixin_test.main();
subreddit_mod_test.main();
subreddit_test.main();
user_content_moderation_test.main();
user_content_test.main();
user_test.main();
utils_test.main();
}
| 0 |
mirrored_repositories/DRAW | mirrored_repositories/DRAW/test/test_config.dart | import 'package:test/test.dart';
import 'package:draw/src/draw_config_context.dart';
void main() {
test('Simple tests for default section of local file.', () {
final configContext = DRAWConfigContext();
expect(configContext.clientId, equals('Y4PJOclpDQy3xZ'));
expect(configContext.clientSecret, equals('UkGLTe6oqsMk5nHCJTHLrwgvHpr'));
expect(configContext.password, equals('pni9ubeht4wd50gk'));
expect(configContext.username, equals('fakebot1'));
});
test('Testing non-default section.', () {
final configContext = DRAWConfigContext(siteName: 'section');
expect(configContext.password, equals('different'));
expect(configContext.oauthUrl, equals('https://oauth.reddit.com'));
});
test(
'Testing non-default section for parameters not present in default site.',
() {
final configContext = DRAWConfigContext(siteName: 'section1');
expect(configContext.password, equals('pni9ubeht4wd50gk'));
expect(configContext.username, equals('sectionbot'));
});
test('Testing non-default parameters with empty strings.', () {
final configContext = DRAWConfigContext(siteName: 'emptyTest');
expect(configContext.username, equals(''));
});
test('Testing default values for unset parameters.', () {
final configContext = DRAWConfigContext();
expect(configContext.shortUrl, equals('https://redd.it'));
expect(configContext.checkForUpdates, equals(false));
expect(configContext.revokeToken,
equals('https://www.reddit.com/api/v1/revoke_token'));
expect(configContext.oauthUrl, equals('oauth.reddit.com'));
expect(configContext.authorizeUrl,
equals('https://reddit.com/api/v1/authorize'));
expect(configContext.accessToken,
equals('https://www.reddit.com/api/v1/access_token'));
});
test('Test for CheckForUpdates Truth value check', () {
final configContext = DRAWConfigContext(siteName: 'testUpdateCheck1');
expect(configContext.checkForUpdates, equals(true));
final configContext1 = DRAWConfigContext(siteName: 'testUpdateCheckOn');
expect(configContext1.checkForUpdates, equals(true));
final configContext2 = DRAWConfigContext(siteName: 'testUpdateCheckTrue');
expect(configContext2.checkForUpdates, equals(true));
final configContext3 = DRAWConfigContext(siteName: 'testUpdateCheckYes');
expect(configContext3.checkForUpdates, equals(true));
final configContext4 = DRAWConfigContext(siteName: 'testUpdateCheckFalse');
expect(configContext4.checkForUpdates, equals(false));
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/submission/submission_test.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> main() async {
Stream<Submission> submissionsHelper(SubredditRef subreddit) {
return subreddit.newest().map<Submission>((u) => u as Submission);
}
test('lib/submission/invalid', () async {
final reddit = await createRedditTestInstance(
'test/submission/lib_submission_invalid.json');
await expectLater(
() async => await reddit.submission(id: 'abcdef').populate(),
throwsA(TypeMatcher<DRAWInvalidSubmissionException>()));
});
test('lib/submission/properties-sanity', () async {
final reddit = await createRedditTestInstance(
'test/submission/lib_submission_properties.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.approvedAt,
DateTime.fromMillisecondsSinceEpoch(1524535384000));
expect(submission.approved, isTrue);
expect(submission.approvedBy!.displayName, 'DRAWApiOfficial');
expect(submission.archived, isFalse);
expect(submission.authorFlairText, isNull);
expect(submission.bannedAt, isNull);
expect(submission.bannedBy, isNull);
expect(submission.brandSafe, isNull);
expect(submission.canGild, isFalse);
expect(submission.canModeratePost, isTrue);
expect(submission.clicked, isFalse);
expect(submission.createdUtc,
DateTime.fromMillisecondsSinceEpoch(1518491082000, isUtc: true));
expect(submission.distinguished, isNull);
expect(submission.domain, 'youtube.com');
expect(submission.downvotes, 0);
expect(submission.edited, isFalse);
expect(submission.hidden, isFalse);
expect(submission.hideScore, isFalse);
expect(submission.ignoreReports, isFalse);
expect(submission.isCrosspostable, isTrue);
expect(submission.isRedditMediaDomain, isFalse);
expect(submission.isSelf, isFalse);
expect(submission.isVideo, isFalse);
expect(submission.vote, VoteState.upvoted);
expect(submission.locked, isFalse);
expect(submission.numComments, 2);
expect(submission.numCrossposts, 0);
expect(submission.over18, isFalse);
expect(submission.pinned, isFalse);
expect(submission.quarantine, isFalse);
expect(submission.removalReason, isNull);
expect(submission.score, 1);
expect(submission.selftext, '');
expect(submission.spam, isFalse);
expect(submission.spoiler, isFalse);
expect(submission.subredditType, 'restricted');
expect(submission.stickied, isFalse);
expect(
submission.title,
'DRAW: Using Dart to Moderate Reddit Comments'
' (DartConf 2018)');
expect(
submission.thumbnail,
Uri.parse(
'https://a.thumbs.redditmedia.com/HP1keD9FPMG7fSBFZQk94HlJ4n13VB13yZagixx0wz4.jpg'));
expect(submission.upvoteRatio, 1.0);
expect(submission.upvotes, 1);
expect(submission.url,
Uri.parse('https://www.youtube.com/watch?v=VqNU_CYVaXg'));
expect(submission.viewCount, 16);
expect(submission.visited, isFalse);
expect(submission.commentSort, CommentSortType.best);
});
test('lib/submission/refresh-comments-sanity', () async {
final reddit = await createRedditTestInstance(
'test/submission/lib_submission_refresh_comments_sanity.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
final originalComments = submission.comments!;
final updatedComments = await submission.refreshComments();
expect(submission.comments, updatedComments);
expect(originalComments.length, updatedComments.length);
});
test('lib/submission/crosspost', () async {
final reddit = await createRedditTestInstance(
'test/submission/lib_submission_crosspost.json',
);
final subreddit = await reddit.subreddit('drawapitesting').populate();
final originalSubmission = await reddit
.submission(
url:
'https://www.reddit.com/r/tf2/comments/7919oe/greetings_from_banana_bay/')
.populate();
await originalSubmission.crosspost(subreddit,
title: 'r/tf2 crosspost'
' test');
});
test('lib/submission/idFromUrl', () {
final urls = [
'http://my.it/2gmzqe/',
'https://redd.it/2gmzqe/',
'http://reddit.com/comments/2gmzqe/',
'https://www.reddit.com/r/redditdev/comments/2gmzqe/'
'praw_https_enabled_praw_testing_needed/'
];
for (final url in urls) {
expect(SubmissionRef.idFromUrl(url), equals('2gmzqe'));
}
});
test('lib/submission/hide-unhide', () async {
final reddit = await createRedditTestInstance(
'test/submission/lib_submission_hide_unhide.json');
final subreddit = reddit.subreddit('drawapitesting');
final submission = await submissionsHelper(subreddit).first;
expect(submission.hidden, isFalse);
await submission.hide();
await submission.refresh();
expect(submission.hidden, isTrue);
await submission.unhide();
await submission.refresh();
expect(submission.hidden, isFalse);
});
test('lib/submission/hide-unhide-multiple', () async {
final reddit = await createRedditTestInstance(
'test/submission/lib_submission_hide_unhide_multiple.json');
final subreddit = reddit.subreddit('drawapitesting');
final submissions = <Submission>[];
await for (final submission in submissionsHelper(subreddit)) {
submissions.add(submission);
expect(submission.hidden, isFalse);
}
expect(submissions.length, equals(3));
await submissions[0].hide(otherSubmissions: submissions.sublist(1));
for (final submission in submissions) {
await submission.refresh();
expect(submission.hidden, isTrue);
}
await submissions[0].unhide(otherSubmissions: submissions.sublist(1));
for (final submission in submissions) {
await submission.refresh();
expect(submission.hidden, isFalse);
}
});
// TODO(bkonyi): We need to also check the post was
// successful.
test('lib/submission/reply', () async {
final reddit = await createRedditTestInstance(
'test/submission/lib_submission_reply.json');
final submission = await (SubmissionRef.withPath(reddit,
r'https://www.reddit.com/r/drawapitesting/comments/7x6ew7/draw_using_dart_to_moderate_reddit_comments/'))
.populate();
await submission.reply('Woohoo!');
});
test('lib/submission/submission_flair', () async {
final reddit = await createRedditTestInstance(
'test/submission/lib_submission_flair.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
final flair = submission.flair;
final choices = await flair.choices();
expect(choices.length, 1);
expect(submission.linkFlairText, null);
await flair.select(choices[0].flairTemplateId,
text: 'Testing Submission Flair');
await submission.refresh();
expect(submission.linkFlairText, 'Testing Submission Flair');
await flair.select(choices[0].flairTemplateId);
await submission.refresh();
expect(submission.linkFlairText, '');
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/messageable_mixin/messageable_mixin_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> main() async {
// TODO(bkonyi): rewrite these to actually check that the messages were
// received. Manually confirmed for now.
test('lib/messageable_mixin/basic_message', () async {
final reddit = await createRedditTestInstance(
'test/messageable_mixin/basic_message.json');
final receiver = reddit.redditor('XtremeCheese');
await receiver.message('Test message', 'Hello XtremeCheese!');
});
test('lib/messageable_mixin/subreddit_message', () async {
final reddit = await createRedditTestInstance(
'test/messageable_mixin/subreddit_message.json');
final receiver = reddit.redditor('Toxicity-Moderator');
final subreddit = reddit.subreddit('drawapitesting');
await receiver.message('Test message', 'Hello Toxicity-Moderator!',
fromSubreddit: subreddit);
});
test('lib/messageable_mixin/invalid_subreddit', () async {
final reddit = await createRedditTestInstance(
'test/messageable_mixin/invalid_subreddit.json');
final receiver = reddit.redditor('Toxicity-Moderator');
final subreddit = reddit.subreddit('drawapitesting2');
await expectLater(
() async => await receiver.message(
'Test message', 'Hello Toxicity-Moderator!',
fromSubreddit: subreddit),
throwsA(TypeMatcher<DRAWInvalidSubredditException>()));
});
test('lib/messageable_mixin/invalid_redditor', () async {
final reddit = await createRedditTestInstance(
'test/messageable_mixin/invalid_redditor.json');
final receiver = reddit.redditor('Toxicity-Moderator2');
final subreddit = reddit.subreddit('drawapitesting');
await expectLater(
() async => await receiver.message(
'Test message', 'Hello Toxicity-Moderator!',
fromSubreddit: subreddit),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/comment/comment_test.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> prettyPrint(comments, depth) async {
if (comments == null) {
return;
}
for (var i = 0; i < comments.length; ++i) {
final tabs = '$depth \t' * depth;
final comment = comments[i];
if (comment is MoreComments) {
expect(
comment.isContinueThisThread || comment.isLoadMoreComments, isTrue);
await prettyPrint(await comment.comments(), depth);
} else {
final body = (await comment.body ?? 'Null');
print(tabs + body);
await prettyPrint(comment.replies, depth + 1);
}
}
}
void submissionChecker(rootSubmission, comments) {
if (comments == null) {
return;
}
for (final c in comments.toList()) {
expect(c.submission.hashCode, rootSubmission.hashCode);
}
}
Future<void> main() async {
test('lib/comment/invalid_comment_test', () async {
final reddit =
await createRedditTestInstance('test/comment/invalid_test.json');
await expectLater(
() async => await CommentRef.withID(reddit, 'abc123').populate(),
throwsA(TypeMatcher<DRAWInvalidCommentException>()));
});
test('lib/comment/continue_test', () async {
final reddit =
await createRedditTestInstance('test/comment/continue_test.json');
final submission = await reddit.submission(id: '7czz1q').populate();
final comments = submission.comments;
final printer = () async {
await prettyPrint(comments, 0);
};
var output = '';
await runZoned(printer, zoneSpecification:
ZoneSpecification(print: (self, parent, zone, message) {
output += message + '\n';
}));
final expected =
File('test/comment/continue_test_expected.out').readAsStringSync();
expect(output, expected);
});
test('lib/comment/more_comment_expand_test', () async {
final reddit =
await createRedditTestInstance('test/comment/more_comment_expand_test');
final comment = await reddit.comment(id: 'e1mnhdn').populate();
submissionChecker(comment.submission, comment.replies);
await comment.replies!.replaceMore();
final printer = () async {
await prettyPrint(<Comment>[comment], 0);
};
var output = '';
var count = 0;
await runZoned(printer, zoneSpecification:
ZoneSpecification(print: (self, parent, zone, message) {
count++;
output += '$count' + message + '\n';
}));
final expected = File('test/comment/more_comment_expand_test_expected.out')
.readAsStringSync();
expect(output, expected);
});
int getMoreCommentsCount(Submission submission) {
var moreComments = 0;
submission.comments!.toList().forEach((v) {
if (v is MoreComments) {
moreComments++;
}
});
return moreComments;
}
void checkNoDuplicates(Submission submission) {
final Set ids = <String?>{};
final comments = submission.comments!.toList();
for (dynamic comment in comments) {
if (ids.contains(comment.fullname)) {
fail('Multiple comments with the same ID are in the CommentForest');
}
ids.add(comment.fullname);
}
}
test('lib/comment/more_comment_count_test', () async {
final reddit = await createRedditTestInstance(
'test/comment/more_comment_count_test.json');
final submission = await reddit.submission(id: 'bpvpfm').populate();
expect(getMoreCommentsCount(submission), 2);
expect(submission.comments!.toList().length, 202);
checkNoDuplicates(submission);
await submission.comments!.replaceMore();
expect(getMoreCommentsCount(submission), 0);
expect(submission.comments!.toList().length, 501);
checkNoDuplicates(submission);
await submission.comments!.replaceMore();
expect(getMoreCommentsCount(submission), 0);
expect(submission.comments!.toList().length, 501);
checkNoDuplicates(submission);
});
test('lib/comment/tons_of_comments_test', () async {
final reddit = await createRedditTestInstance(
'test/comment/tons_of_comments_test.json');
final submission = await reddit.submission(id: '7gylz9').populate();
final comments = submission.comments;
submissionChecker(submission, comments);
final printer = () async {
await prettyPrint(comments, 0);
};
var output = '';
var count = 0;
await runZoned(printer, zoneSpecification:
ZoneSpecification(print: (self, parent, zone, message) {
count++;
output += '$count' + message + '\n';
}));
final expected =
File('test/comment/tons_of_comments_expected.out').readAsStringSync();
expect(output, equals(expected));
});
test('lib/comment/comment_ref_test', () async {
final reddit =
await createRedditTestInstance('test/comment/comment_ref_test.json');
final comment = await reddit.comment(id: 'dxj0i8m').populate();
final commentWithPath = await reddit
.comment(
url:
'https://www.reddit.com/r/pics/comments/8cz8v0/owls_born_outside_of_office_window_wont_stop/dxj0i8m/')
.populate();
expect(
comment.body, '“ ok class, everyone have a look into our Humanarium”');
expect(commentWithPath.body, comment.body);
expect(commentWithPath.id, comment.id);
expect(comment.id, 'dxj0i8m');
expect(comment.submission.shortlink, commentWithPath.submission.shortlink);
});
test('lib/comment/comment_properties_test', () async {
final reddit =
await createRedditTestInstance('test/comment/continue_test.json');
final submission = await reddit.submission(id: '7czz1q').populate();
final comment = submission.comments![0] as Comment;
expect(comment.approved, isFalse);
expect(comment.approvedAtUtc, isNull);
expect(comment.approvedBy, isNull);
expect(comment.archived, isFalse);
expect(comment.authorFlairText, isNull);
expect(comment.bannedAtUtc, isNull);
expect(comment.bannedBy, isNull);
expect(comment.canGild, isFalse);
expect(comment.canModPost, isTrue);
expect(comment.collapsed, isFalse);
expect(comment.collapsedReason, isNull);
expect(comment.createdUtc,
DateTime.fromMillisecondsSinceEpoch(1510703692 * 1000, isUtc: true));
expect(comment.depth, 0);
expect(comment.downvotes, 0);
expect(comment.edited, isFalse);
expect(comment.ignoreReports, isFalse);
expect(comment.isSubmitter, isTrue);
expect(comment.vote, VoteState.upvoted);
expect(comment.linkId, 't3_7czz1q');
expect(comment.numReports, 0);
expect(comment.parentId, 't3_7czz1q');
expect(comment.permalink,
'/r/drawapitesting/comments/7czz1q/testing/dpty59t/');
expect(comment.removalReason, isNull);
expect(comment.removed, isFalse);
expect(comment.saved, isFalse);
expect(comment.score, 1);
expect(comment.scoreHidden, isFalse);
expect(comment.spam, isFalse);
expect(comment.stickied, isFalse);
expect(comment.subreddit, reddit.subreddit('drawapitesting'));
expect(comment.subredditId, 't5_3mqw1');
expect(comment.subredditType, 'restricted');
expect(comment.upvotes, 1);
expect(comment.isRoot, isTrue);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/multireddit/multireddit_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:color/color.dart';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> main() async {
final expectedSubredditList = [
{'name': 'solotravel'},
{'name': 'Fishing'},
{'name': 'geocaching'},
{'name': 'Yosemite'},
{'name': 'CampingandHiking'},
{'name': 'whitewater'},
{'name': 'remoteplaces'},
{'name': 'Adirondacks'},
{'name': 'caving'},
{'name': 'travelphotos'},
{'name': 'canyoneering'},
{'name': 'Backcountry'},
{'name': 'Bushcraft'},
{'name': 'Kayaking'},
{'name': 'scuba'},
{'name': 'bouldering'},
{'name': 'CampingGear'},
{'name': 'urbanexploration'},
{'name': 'WWOOF'},
{'name': 'adventures'},
{'name': 'climbing'},
{'name': 'Mountaineering'},
{'name': 'sailing'},
{'name': 'hiking'},
{'name': 'iceclimbing'},
{'name': 'tradclimbing'},
{'name': 'backpacking'},
{'name': 'trailmeals'},
{'name': 'Climbingvids'},
{'name': 'camping'},
{'name': 'climbharder'},
{'name': 'skiing'},
{'name': 'Outdoors'},
{'name': 'alpinism'},
{'name': 'PacificCrestTrail'},
{'name': 'Ultralight'},
{'name': 'Hammocks'},
{'name': 'AppalachianTrail'}
];
test('lib/multireddit/copy_parse_constructor_basic', () async {
final reddit = await createRedditTestInstance(
'test/multireddit/lib_multireddit_copy.json');
final data = {
'kind': 'LabeledMulti',
'data': {
'can_edit': false,
'display_name': 'adventure',
'name': 'adventure',
'subreddits': expectedSubredditList,
'path': '/user/MyFifthOne/m/adventure/',
}
};
final multireddit = Multireddit.parse(reddit, data);
final newMulti = await multireddit.copy('test-copy-adventure-2');
expect(newMulti.displayName, 'test_copy_adventure_2');
expect(newMulti.subreddits, multireddit.subreddits);
});
test('lib/multireddit/copy_without_parsing_basic', () async {
final newMultiName = 'CopyOfMultireddit';
final newMultiNameSlug = 'copyofmultireddit';
final reddit = await createRedditTestInstance(
'test/multireddit/lib_multireddit_copy_2.json');
final oldMulti = (await reddit.user.multireddits())![1];
final newMulti = await oldMulti.copy(newMultiName);
expect(newMulti.displayName, newMultiNameSlug);
expect(newMulti.subreddits, oldMulti.subreddits);
});
test('lib/multireddit/multis_from_user_non_trival', () async {
final reddit = await createRedditTestInstance(
'test/multireddit/lib_user_multireddits.json');
final multis = (await reddit.user.multireddits()) as List<Multireddit>;
expect(multis.length, 9);
final multi = multis[1];
// Testing using data variable.
expect(multi.data!['name'], 'drawtestingmulti');
expect(multi.data!['display_name'], 'drawtestingmulti');
expect(multi.data!['can_edit'], isTrue);
expect(multi.data!['subreddits'].length, 81);
// Testing using getters.
expect(multi.author.displayName, (await reddit.user.me())!.displayName);
expect(multi.over18, isFalse);
expect(multi.keyColor, HexColor('#cee3f8'));
expect(multi.visibility, Visibility.public);
expect(multi.weightingScheme, WeightingScheme.classic);
expect(multi.iconName, isNull);
expect(multi.displayName, 'drawtestingmulti');
expect(multi.fullname, 'drawtestingmulti');
expect(multi.canEdit, isTrue);
expect(multi.subreddits.length, 81);
});
test('lib/multireddit/delete_multi_basic', () async {
final reddit = await createRedditTestInstance(
'test/multireddit/lib_multireddit_delete.json',
);
final multis = (await reddit.user.multireddits()) as List<Multireddit>;
expect(multis.length, 5);
await multis[1].delete();
final newMultis = (await reddit.user.multireddits()) as List<Multireddit>;
expect(newMultis.length, 4);
});
test('lib/multireddit/add_subreddit_basic', () async {
final reddit = await createRedditTestInstance(
'test/multireddit/lib_multireddit_add_subreddit.json',
);
final multis = (await reddit.user.multireddits()) as List<Multireddit>;
final multi = multis[1];
await multi.add('camping');
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/user_content/user_content_test.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> main() async {
Stream<Submission> submissionsHelper(SubredditRef subreddit) {
return subreddit.newest().cast<Submission>();
}
test('lib/user_content/replyable', () async {
final reddit = await createRedditTestInstance(
'test/user_content/lib_user_content_replyable.json');
final subreddit = reddit.subreddit('drawapitesting');
final submission =
await subreddit.submit('Replyable submission', selftext: 'Testing!');
final comment = await submission.reply('Test comment!');
expect(comment.body, equals('Test comment!'));
await submission.delete();
await comment.delete();
});
test('lib/user_content/reportable', () async {
final reddit = await createRedditTestInstance(
'test/user_content/lib_user_content_reportable.json');
final subreddit = reddit.subreddit('drawapitesting');
final submission = await subreddit.submit('Reportable submission',
selftext: 'Rule'
' breaking!');
await submission.report('Breaks rule 42');
await submission.refresh();
expect(submission.modReports[0],
equals(<String>['Breaks rule 42', 'DRAWApiOfficial']));
await submission.delete();
});
// There doesn't seem to be a way to check if inbox replies are enabled or
// disabled through the API, so we're just going to check that the API calls
// don't crash anything.
// TODO(bkonyi): find out if we can see if inbox replies are enabled through
// the API.
test('lib/user_content/inbox_toggleable', () async {
final reddit = await createRedditTestInstance(
'test/user_content/lib_user_content_toggleable.json');
final subreddit = reddit.subreddit('drawapitesting');
final submission =
await subreddit.submit('Editable submission', selftext: 'Testing!');
await submission.disableInboxReplies();
await submission.enableInboxReplies();
});
test('lib/user_content/saveable', () async {
final reddit = await createRedditTestInstance(
'test/user_content/lib_user_content_saveable.json');
final subreddit = reddit.subreddit('drawapitesting');
final submission =
await subreddit.submit('Saveable submission', selftext: 'Testing!');
await submission.refresh();
expect(submission.saved, isFalse);
await submission.save();
await submission.refresh();
expect(submission.saved, isTrue);
await submission.unsave();
await submission.refresh();
expect(submission.saved, isFalse);
await submission.delete();
});
test('lib/user_content/submit-editable-delete', () async {
final reddit = await createRedditTestInstance(
'test/user_content/lib_user_content_editable.json');
final subreddit = reddit.subreddit('drawapitesting');
final submission =
await subreddit.submit('Editable submission', selftext: 'Testing!');
await submission.refresh();
expect(submission.selftext, equals('Testing!'));
await submission.edit('Edited!');
expect(submission.selftext, equals('Edited!'));
await submission.delete();
});
test('lib/user_content/votes', () async {
final reddit = await createRedditTestInstance(
'test/user_content/lib_user_content_votes.json');
final redditor = reddit.redditor('DRAWApiOfficial');
Future<List<String>> getUpvoted() async {
final upvoted = <String>[];
await for (final submission in redditor.upvoted()) {
expect(submission is Submission, isTrue);
upvoted.add((submission as Submission).fullname!);
}
return upvoted;
}
Future<List<String>> getDownvoted() async {
final upvoted = <String>[];
await for (final submission in redditor.downvoted()) {
expect(submission is Submission, isTrue);
upvoted.add((submission as Submission).fullname!);
}
return upvoted;
}
final subreddit = reddit.subreddit('drawapitesting');
var upvoted = await getUpvoted();
var downvoted = await getDownvoted();
await for (final submission in submissionsHelper(subreddit)) {
expect(upvoted.contains(submission.fullname), isFalse);
expect(downvoted.contains(submission.fullname), isFalse);
await submission.upvote();
}
upvoted = await getUpvoted();
downvoted = await getDownvoted();
await for (final submission in submissionsHelper(subreddit)) {
expect(upvoted.contains(submission.fullname), isTrue);
expect(downvoted.contains(submission.fullname), isFalse);
await submission.downvote();
}
upvoted = await getUpvoted();
downvoted = await getDownvoted();
await for (final submission in submissionsHelper(subreddit)) {
expect(upvoted.contains(submission.fullname), isFalse);
expect(downvoted.contains(submission.fullname), isTrue);
await submission.clearVote();
}
upvoted = await getUpvoted();
downvoted = await getDownvoted();
await for (final submission in submissionsHelper(subreddit)) {
expect(upvoted.contains(submission.fullname), isFalse);
expect(downvoted.contains(submission.fullname), isFalse);
}
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/frontpage/frontpage_test.dart | // Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:draw/draw.dart';
import '../test_utils.dart';
Future<void> main() async {
// TODO(bkonyi): this is more of a sanity check, but all the functionality in
// [FrontPage] should have been tested elsewhere. Might want to expand this
// coverage anyway.
test('lib/frontpage/sanity', () async {
final reddit = await createRedditTestInstance(
'test/frontpage/lib_frontpage_sanity.json');
await for (final hot in reddit.front.hot(params: {'limit': '10'})) {
expect(hot is Submission, isTrue);
}
});
test('lib/frontpage/best', () async {
final reddit = await createRedditTestInstance(
'test/frontpage/lib_frontpage_best.json');
await for (final hot in reddit.front.best(params: {'limit': '10'})) {
expect(hot is Submission, isTrue);
}
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/unit_tests/enum_stringify_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'package:test/test.dart';
import 'package:draw/src/listing/mixins/base.dart';
import 'package:draw/src/models/multireddit.dart';
import 'package:draw/src/models/mixins/user_content_moderation.dart';
import 'package:draw/src/models/submission_impl.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:draw/src/models/subreddit_moderation.dart';
import 'package:draw/src/util.dart';
void main() {
test('commentSortTypeToString', () {
expect(commentSortTypeToString(CommentSortType.confidence), 'confidence');
expect(commentSortTypeToString(CommentSortType.top), 'top');
expect(commentSortTypeToString(CommentSortType.newest), 'new');
expect(commentSortTypeToString(CommentSortType.controversial),
'controversial');
expect(commentSortTypeToString(CommentSortType.old), 'old');
expect(commentSortTypeToString(CommentSortType.random), 'random');
expect(commentSortTypeToString(CommentSortType.qa), 'qa');
expect(commentSortTypeToString(CommentSortType.blank), 'blank');
});
test('distinctionTypeToString', () {
expect(distinctionTypeToString(DistinctionType.admin), 'admin');
expect(distinctionTypeToString(DistinctionType.no), 'no');
expect(distinctionTypeToString(DistinctionType.special), 'special');
expect(distinctionTypeToString(DistinctionType.yes), 'yes');
});
test('iconNameToString', () {
expect(iconNameToString(IconName.artAndDesign), 'art and design');
expect(iconNameToString(IconName.ask), 'ask');
expect(iconNameToString(IconName.books), 'books');
expect(iconNameToString(IconName.business), 'business');
expect(iconNameToString(IconName.cars), 'cars');
expect(iconNameToString(IconName.comic), 'comics');
expect(iconNameToString(IconName.cuteAnimals), 'cute animals');
expect(iconNameToString(IconName.diy), 'diy');
expect(iconNameToString(IconName.entertainment), 'entertainment');
expect(iconNameToString(IconName.foodAndDrink), 'food and drink');
expect(iconNameToString(IconName.funny), 'funny');
expect(iconNameToString(IconName.games), 'games');
expect(iconNameToString(IconName.grooming), 'grooming');
expect(iconNameToString(IconName.health), 'health');
expect(iconNameToString(IconName.lifeAdvice), 'life advice');
expect(iconNameToString(IconName.military), 'military');
expect(iconNameToString(IconName.modelsPinup), 'models pinup');
expect(iconNameToString(IconName.music), 'music');
expect(iconNameToString(IconName.news), 'news');
expect(iconNameToString(IconName.philosophy), 'philosophy');
expect(iconNameToString(IconName.picturesAndGifs), 'pictures and gifs');
expect(iconNameToString(IconName.science), 'science');
expect(iconNameToString(IconName.shopping), 'shopping');
expect(iconNameToString(IconName.sports), 'sports');
expect(iconNameToString(IconName.style), 'style');
expect(iconNameToString(IconName.tech), 'tech');
expect(iconNameToString(IconName.travel), 'travel');
expect(iconNameToString(IconName.unusualStories), 'unusual stories');
expect(iconNameToString(IconName.video), 'video');
expect(iconNameToString(IconName.emptyString), '');
expect(iconNameToString(IconName.none), 'None');
});
test('moderatorActionTypeToString', () {
expect(
moderatorActionTypesToString(ModeratorActionType.acceptModeratorInvite),
'acceptmoderatorinvite');
expect(moderatorActionTypesToString(ModeratorActionType.addContributor),
'addcontributor');
expect(moderatorActionTypesToString(ModeratorActionType.addModerator),
'addmoderator');
expect(moderatorActionTypesToString(ModeratorActionType.approveComment),
'approvecomment');
expect(moderatorActionTypesToString(ModeratorActionType.approveLink),
'approvelink');
expect(
moderatorActionTypesToString(ModeratorActionType.banUser), 'banuser');
expect(moderatorActionTypesToString(ModeratorActionType.communityStyling),
'community_styling');
expect(moderatorActionTypesToString(ModeratorActionType.communityWidgets),
'community_widgets');
expect(moderatorActionTypesToString(ModeratorActionType.createRule),
'createrule');
expect(moderatorActionTypesToString(ModeratorActionType.deleteRule),
'deleterule');
expect(moderatorActionTypesToString(ModeratorActionType.distinguish),
'distinguish');
expect(moderatorActionTypesToString(ModeratorActionType.editFlair),
'editflair');
expect(
moderatorActionTypesToString(ModeratorActionType.editRule), 'editrule');
expect(moderatorActionTypesToString(ModeratorActionType.editSettings),
'editsettings');
expect(moderatorActionTypesToString(ModeratorActionType.ignoreReports),
'ignorereports');
expect(moderatorActionTypesToString(ModeratorActionType.inviteModerator),
'invitemoderator');
expect(moderatorActionTypesToString(ModeratorActionType.lock), 'lock');
expect(
moderatorActionTypesToString(ModeratorActionType.markNSFW), 'marknsfw');
expect(moderatorActionTypesToString(ModeratorActionType.modmailEnrollment),
'modmail_enrollment');
expect(
moderatorActionTypesToString(ModeratorActionType.muteUser), 'muteuser');
expect(moderatorActionTypesToString(ModeratorActionType.removeComment),
'removecomment');
expect(moderatorActionTypesToString(ModeratorActionType.removeContributor),
'removecontributor');
expect(moderatorActionTypesToString(ModeratorActionType.removeLink),
'removelink');
expect(moderatorActionTypesToString(ModeratorActionType.removeModerator),
'removemoderator');
expect(
moderatorActionTypesToString(ModeratorActionType.removeWikiContributor),
'removewikicontributor');
expect(moderatorActionTypesToString(ModeratorActionType.setContestMode),
'setcontestmode');
expect(moderatorActionTypesToString(ModeratorActionType.setPermissions),
'setpermissions');
expect(moderatorActionTypesToString(ModeratorActionType.setSuggestedSort),
'setsuggestedsort');
expect(moderatorActionTypesToString(ModeratorActionType.spamComment),
'spamcomment');
expect(
moderatorActionTypesToString(ModeratorActionType.spamLink), 'spamlink');
expect(
moderatorActionTypesToString(ModeratorActionType.spoiler), 'spoiler');
expect(moderatorActionTypesToString(ModeratorActionType.sticky), 'sticky');
expect(moderatorActionTypesToString(ModeratorActionType.unbanUser),
'unbanuser');
expect(moderatorActionTypesToString(ModeratorActionType.unignoreReports),
'unignorereports');
expect(moderatorActionTypesToString(ModeratorActionType.uninviteModerator),
'uninvitemoderator');
expect(moderatorActionTypesToString(ModeratorActionType.unlock), 'unlock');
expect(moderatorActionTypesToString(ModeratorActionType.unmuteUser),
'unmuteuser');
expect(moderatorActionTypesToString(ModeratorActionType.unsetContestMode),
'unsetcontestmode');
expect(moderatorActionTypesToString(ModeratorActionType.unspoiler),
'unspoiler');
expect(
moderatorActionTypesToString(ModeratorActionType.unsticky), 'unsticky');
expect(moderatorActionTypesToString(ModeratorActionType.wikiBanned),
'wikibanned');
expect(moderatorActionTypesToString(ModeratorActionType.wikiContributor),
'wikicontributor');
expect(moderatorActionTypesToString(ModeratorActionType.wikiPageListed),
'wikipagelisted');
expect(moderatorActionTypesToString(ModeratorActionType.wikiPermLevel),
'wikipermlevel');
expect(moderatorActionTypesToString(ModeratorActionType.wikiRevise),
'wikirevise');
expect(moderatorActionTypesToString(ModeratorActionType.wikiUnbanned),
'wikiunbanned');
});
test('searchSyntaxToString', () {
expect(searchSyntaxToString(SearchSyntax.cloudSearch), 'cloudsearch');
expect(searchSyntaxToString(SearchSyntax.lucene), 'lucene');
expect(searchSyntaxToString(SearchSyntax.plain), 'plain');
});
test('subredditTypeToString', () {
expect(subredditTypeToString(SubredditType.archivedSubreddit), 'archived');
expect(subredditTypeToString(SubredditType.employeesOnlySubreddit),
'employees_only');
expect(subredditTypeToString(SubredditType.goldOnlySubreddit), 'gold_only');
expect(subredditTypeToString(SubredditType.goldRestrictedSubreddit),
'gold_restricted');
expect(subredditTypeToString(SubredditType.privateSubreddit), 'private');
expect(subredditTypeToString(SubredditType.publicSubreddit), 'public');
expect(
subredditTypeToString(SubredditType.restrictedSubreddit), 'restricted');
});
test('stringToModeratorActionType', () {
expect(stringToModeratorActionType('acceptmoderatorinvite'),
ModeratorActionType.acceptModeratorInvite);
expect(stringToModeratorActionType('addcontributor'),
ModeratorActionType.addContributor);
expect(stringToModeratorActionType('addmoderator'),
ModeratorActionType.addModerator);
expect(stringToModeratorActionType('approvecomment'),
ModeratorActionType.approveComment);
expect(stringToModeratorActionType('approvelink'),
ModeratorActionType.approveLink);
expect(stringToModeratorActionType('banuser'), ModeratorActionType.banUser);
expect(stringToModeratorActionType('community_styling'),
ModeratorActionType.communityStyling);
expect(stringToModeratorActionType('community_widgets'),
ModeratorActionType.communityWidgets);
expect(stringToModeratorActionType('createrule'),
ModeratorActionType.createRule);
expect(stringToModeratorActionType('deleterule'),
ModeratorActionType.deleteRule);
expect(stringToModeratorActionType('distinguish'),
ModeratorActionType.distinguish);
expect(stringToModeratorActionType('editflair'),
ModeratorActionType.editFlair);
expect(
stringToModeratorActionType('editrule'), ModeratorActionType.editRule);
expect(stringToModeratorActionType('editsettings'),
ModeratorActionType.editSettings);
expect(stringToModeratorActionType('ignorereports'),
ModeratorActionType.ignoreReports);
expect(stringToModeratorActionType('invitemoderator'),
ModeratorActionType.inviteModerator);
expect(stringToModeratorActionType('lock'), ModeratorActionType.lock);
expect(
stringToModeratorActionType('marknsfw'), ModeratorActionType.markNSFW);
expect(stringToModeratorActionType('modmail_enrollment'),
ModeratorActionType.modmailEnrollment);
expect(
stringToModeratorActionType('muteuser'), ModeratorActionType.muteUser);
expect(stringToModeratorActionType('removecomment'),
ModeratorActionType.removeComment);
expect(stringToModeratorActionType('removecontributor'),
ModeratorActionType.removeContributor);
expect(stringToModeratorActionType('removelink'),
ModeratorActionType.removeLink);
expect(stringToModeratorActionType('removemoderator'),
ModeratorActionType.removeModerator);
expect(stringToModeratorActionType('removewikicontributor'),
ModeratorActionType.removeWikiContributor);
expect(stringToModeratorActionType('setcontestmode'),
ModeratorActionType.setContestMode);
expect(stringToModeratorActionType('setpermissions'),
ModeratorActionType.setPermissions);
expect(stringToModeratorActionType('setsuggestedsort'),
ModeratorActionType.setSuggestedSort);
expect(stringToModeratorActionType('spamcomment'),
ModeratorActionType.spamComment);
expect(
stringToModeratorActionType('spamlink'), ModeratorActionType.spamLink);
expect(stringToModeratorActionType('spoiler'), ModeratorActionType.spoiler);
expect(stringToModeratorActionType('sticky'), ModeratorActionType.sticky);
expect(stringToModeratorActionType('unbanuser'),
ModeratorActionType.unbanUser);
expect(stringToModeratorActionType('unignorereports'),
ModeratorActionType.unignoreReports);
expect(stringToModeratorActionType('uninvitemoderator'),
ModeratorActionType.uninviteModerator);
expect(stringToModeratorActionType('unlock'), ModeratorActionType.unlock);
expect(stringToModeratorActionType('unmuteuser'),
ModeratorActionType.unmuteUser);
expect(stringToModeratorActionType('unsetcontestmode'),
ModeratorActionType.unsetContestMode);
expect(stringToModeratorActionType('unspoiler'),
ModeratorActionType.unspoiler);
expect(
stringToModeratorActionType('unsticky'), ModeratorActionType.unsticky);
expect(stringToModeratorActionType('wikibanned'),
ModeratorActionType.wikiBanned);
expect(stringToModeratorActionType('wikicontributor'),
ModeratorActionType.wikiContributor);
expect(stringToModeratorActionType('wikipagelisted'),
ModeratorActionType.wikiPageListed);
expect(stringToModeratorActionType('wikipermlevel'),
ModeratorActionType.wikiPermLevel);
expect(stringToModeratorActionType('wikirevise'),
ModeratorActionType.wikiRevise);
expect(stringToModeratorActionType('wikiunbanned'),
ModeratorActionType.wikiUnbanned);
});
test('stringToSubredditType', () {
expect(stringToSubredditType('archived'), SubredditType.archivedSubreddit);
expect(stringToSubredditType('employees_only'),
SubredditType.employeesOnlySubreddit);
expect(stringToSubredditType('gold_only'), SubredditType.goldOnlySubreddit);
expect(stringToSubredditType('gold_restricted'),
SubredditType.goldRestrictedSubreddit);
expect(stringToSubredditType('private'), SubredditType.privateSubreddit);
expect(stringToSubredditType('public'), SubredditType.publicSubreddit);
expect(
stringToSubredditType('restricted'), SubredditType.restrictedSubreddit);
});
test('timeFilterToString', () {
expect(timeFilterToString(TimeFilter.all), 'all');
expect(timeFilterToString(TimeFilter.day), 'day');
expect(timeFilterToString(TimeFilter.hour), 'hour');
expect(timeFilterToString(TimeFilter.month), 'month');
expect(timeFilterToString(TimeFilter.week), 'week');
expect(timeFilterToString(TimeFilter.year), 'year');
});
test('sortToString', () {
expect(sortToString(Sort.comments), 'comments');
expect(sortToString(Sort.hot), 'hot');
expect(sortToString(Sort.newest), 'new');
expect(sortToString(Sort.relevance), 'relevance');
expect(sortToString(Sort.top), 'top');
});
test('visibilityToString', () {
expect(visibilityToString(Visibility.hidden), 'hidden');
expect(visibilityToString(Visibility.private), 'private');
expect(visibilityToString(Visibility.public), 'public');
});
test('weightingSchemeToString', () {
expect(weightingSchemeToString(WeightingScheme.classic), 'classic');
expect(weightingSchemeToString(WeightingScheme.fresh), 'fresh');
});
test('moderatorPermissionToString', () {
expect(moderatorPermissionToString(ModeratorPermission.all), 'all');
expect(moderatorPermissionToString(ModeratorPermission.access), 'access');
expect(moderatorPermissionToString(ModeratorPermission.config), 'config');
expect(moderatorPermissionToString(ModeratorPermission.flair), 'flair');
expect(moderatorPermissionToString(ModeratorPermission.mail), 'mail');
expect(moderatorPermissionToString(ModeratorPermission.posts), 'posts');
expect(moderatorPermissionToString(ModeratorPermission.wiki), 'wiki');
});
test('modmailStateToString', () {
expect(modmailStateToString(ModmailState.all), 'all');
expect(modmailStateToString(ModmailState.archived), 'archived');
expect(modmailStateToString(ModmailState.highlighted), 'highlighted');
expect(modmailStateToString(ModmailState.inprogress), 'inprogress');
expect(modmailStateToString(ModmailState.mod), 'mod');
expect(modmailStateToString(ModmailState.newmail), 'new');
expect(modmailStateToString(ModmailState.notifications), 'notifications');
});
test('modmailSortToString', () {
expect(modmailSortToString(ModmailSort.mod), 'mod');
expect(modmailSortToString(ModmailSort.recent), 'recent');
expect(modmailSortToString(ModmailSort.unread), 'unread');
expect(modmailSortToString(ModmailSort.user), 'user');
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/unit_tests/test_draw_config_context.dart | import 'dart:io';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import 'package:draw/src/draw_config_context.dart';
//Mocking
class MockPlatform extends Mock implements Platform {}
/*
//TODO(ckartik): Utilize mirrors lib here to get access to private methods.
void _testUserConfigPathGetter() {
//Platform os = new MockPlatform();
final dummy_mac_envs = {
'TERM_SESSION_ID': 'w0t0p0:8DC4D1FE-DF20-48B5-824E-56692EB7F544',
'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.7oRE2BfsAa/Listeners',
'Apple_PubSub_Socket_Render':
'/private/tmp/com.apple.launchd.07ZqI5EHtp/Render',
'COLORFGBG': '7;0',
'ITERM_PROFILE': 'Dark',
'XPC_FLAGS': '0x0',
'LANG': 'en_US.UTF-8',
'PWD': '/Users/krishchopra/src/DRAW/mockito_tests/src',
'SHELL': '/bin/zsh',
'TERM_PROGRAM_VERSION': '3.1.4',
'TERM_PROGRAM': 'iTerm.app',
'PATH':
'/Users/krishchopra/.rvm/gems/ruby-2.2.1/bin:/Users/krishchopra/.rvm/gems/ruby-2.2.1@global/bin:/Users/krishchopra/.rvm/rubies/ruby-2.2.1/bin:/Users/krishchopra/flutter/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/Applications/Racket v6.2.1/bin:/Library/TeX/texbin:~/.pub-cache/bin:/Users/krishchopra/.fzf/bin:/Users/krishchopra/.rvm/bin',
'DISPLAY':
'/private/tmp/com.apple.launchd.d7TtJnpcM3/org.macosforge.xquartz:0',
'COLORTERM': 'truecolor',
'TERM': 'xterm-256color',
'HOME': '/Users/krishchopra',
'TMPDIR': '/var/folders/nt/hdfptzsd5w9gy38mp9rpttnw0000gn/T/',
'USER': 'krishchopra',
'XPC_SERVICE_NAME': '0',
'LOGNAME': 'krishchopra',
'__CF_USER_TEXT_ENCODING': '0x1F5:0x0:0x0',
'ITERM_SESSION_ID': 'w0t0p0:8DC4D1FE-DF20-48B5-824E-56692EB7F544',
'SHLVL': '1',
'OLDPWD': '/Users/krishchopra/src/DRAW/mockito_tests',
'ZSH': '/Users/krishchopra/.oh-my-zsh',
'PAGER': 'less',
'LESS': '-R',
'LC_CTYPE': 'en_US.UTF-8',
'LSCOLORS': 'Gxfxcxdxbxegedabagacad',
'rvm_prefix': '/Users/krishchopra',
'rvm_path': '/Users/krishchopra/.rvm',
'rvm_bin_path': '/Users/krishchopra/.rvm/bin',
'_system_type': 'Darwin',
'_system_name': 'OSX',
'_system_version': '10.12',
'_system_arch': 'x86_64',
'rvm_version': '1.27.0 (latest)',
'GEM_HOME': '/Users/krishchopra/.rvm/gems/ruby-2.2.1',
'GEM_PATH':
'/Users/krishchopra/.rvm/gems/ruby-2.2.1:/Users/krishchopra/.rvm/gems/ruby-2.2.1@global',
'MY_RUBY_HOME': '/Users/krishchopra/.rvm/rubies/ruby-2.2.1',
'IRBRC': '/Users/krishchopra/.rvm/rubies/ruby-2.2.1/.irbrc',
'RUBY_VERSION': 'ruby-2.2.1',
'rvm_alias_expanded': '',
'rvm_bin_flag': '',
'rvm_docs_type': '',
'rvm_gemstone_package_file': '',
'rvm_gemstone_url': '',
'rvm_niceness': '',
'rvm_nightly_flag': '',
'rvm_only_path_flag': '',
'rvm_proxy': '',
'rvm_quiet_flag': '',
'rvm_ruby_bits': '',
'rvm_ruby_file': '',
'rvm_ruby_make': '',
'rvm_ruby_make_install': '',
'rvm_ruby_mode': '',
'rvm_script_name': '',
'rvm_sdk': '',
'rvm_silent_flag': '',
'rvm_use_flag': '',
'rvm_wrapper_name': '',
'rvm_hook': '',
'_': '/usr/local/bin/dart'
};
//Mac Stubbing
//when(os.enviroment).thenReturn(dummy_mac_envs);
}
*/
void main() {
// Given an range of different inputs for [checkForUpdates],
// verify the resulting bool for checkForUpdates.
group('checkForUpdates: ', () {
test('false', () {
final expectedTruthValue = false;
final falseValues = [false, 'False', 'other', 'anything', '0', 0];
for (var value in falseValues) {
final config = DRAWConfigContext(checkForUpdates: value);
expect(config.checkForUpdates, expectedTruthValue);
}
});
test('true', () {
final expectedTruthValue = true;
final trueValues = [true, '1', 'true', 'YES', 'on'];
for (var value in trueValues) {
final config = DRAWConfigContext(checkForUpdates: value);
assert(
config.checkForUpdates == expectedTruthValue, 'failed on $value');
}
});
});
test('DRAWConfigContext sanity', () async {
final config = DRAWConfigContext(configUrl: 'test/unit_tests/test.ini');
expect(config.accessToken, 'abc123');
expect(config.authorizeUrl, 'https://www.reddit.com/api/v1/authorize');
expect(config.clientId, 'Y4PJOclpDQy3xZ');
expect(config.clientSecret, 'UkGLTe6oqsMk5nHCJTHLrwgvHpr');
expect(config.commentKind, 't1');
expect(config.configUrl, 'test/unit_tests/test.ini');
expect(config.httpProxy, 'http://proxy1.com');
expect(config.httpsProxy, 'https://proxy1-secure.com');
expect(config.messageKind, 't_10');
expect(config.oauthUrl, 'oauth.reddit.com');
expect(config.password, 'pni9ubeht4wd50gk');
expect(config.redditUrl, 'https://www.reddit_test.com');
expect(config.redditorKind, 't2');
expect(config.redirectUrl, 'www.google.com');
expect(config.refreshToken, 'refresh123');
expect(config.revokeToken, 'revoke123');
expect(config.submissionKind, 't3');
expect(config.subredditKind, 't5');
expect(config.userAgent, 'foobar');
expect(config.username, 'fakebot1');
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/unit_tests/utils_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'package:test/test.dart';
import 'package:draw/src/util.dart';
void main() {
test('BoundedSet', () {
final bounded = BoundedSet<int>(5);
for (var i = 0; i < 5; ++i) {
bounded.add(i);
expect(bounded.contains(i), isTrue);
}
expect(bounded.contains(6), isFalse);
bounded.add(6);
expect(bounded.contains(6), isTrue);
expect(bounded.contains(0), isFalse);
});
test('ExponentialCounter', () {
final counter = ExponentialCounter(5);
for (var i = 0; i < 25; ++i) {
expect(counter.counter() <= 5.0, isTrue);
}
counter.reset();
expect(counter.counter() <= 2.0, isTrue);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/user/user_test.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:draw/draw.dart';
import '../test_utils.dart';
Future<void> main() async {
test('lib/user/me', () async {
final reddit = await createRedditTestInstance('test/user/lib_user_me.json');
final me = (await reddit.user.me()) as Redditor;
expect(me.displayName, equals('DRAWApiOfficial'));
expect(me.isEmployee, isFalse);
expect(me.preferNoProfanity, isTrue);
expect(me.isSuspended, isFalse);
expect(me.commentKarma, equals(0));
expect(me.linkKarma, equals(1));
expect(me.goldCreddits, equals(0));
expect(me.createdUtc!.millisecondsSinceEpoch / 1000, equals(1501801979));
});
test('lib/user/blocked', () async {
// TODO(bkonyi): Actually block some users and update this test.
/*
final reddit = await createRedditTestInstance(
'test/user/lib_user_blocked.json');
final List<Redditor> blocked = await reddit.user.blocked();
expect(blocked.length, equals(0));
*/
});
test('lib/user/contributorSubreddits', () async {
final reddit = await createRedditTestInstance(
'test/user/lib_user_contributorSubreddits.json');
final subreddits = <Subreddit>[];
await for (final subreddit
in reddit.user.contributorSubreddits(limit: 101)) {
subreddits.add(subreddit);
}
expect(subreddits.length, equals(1));
final subreddit = subreddits[0];
expect(subreddit.displayName, equals('drawapitesting'));
expect(subreddit.isContributor, isTrue);
expect(subreddit.isBanned, isFalse);
});
test('lib/user/friends', () async {
final reddit =
await createRedditTestInstance('test/user/lib_user_friends.json');
final friends = await reddit.user.friends();
expect(friends.length, equals(1));
final friend = friends[0];
expect(friend.displayName, equals('XtremeCheese'));
expect(friend.data!['date'], equals(1501884713.0));
});
test('lib/user/karma', () async {
// TODO(bkonyi): Actually get some karma and update this test.
/*final reddit = await createRedditTestInstance(
'test/user/lib_user_karma.json', live: true);
final Map<Subreddit, Map<String, int>> karma = await reddit.user.karma();*/
});
test('lib/user/moderatorSubreddits', () async {
final reddit = await createRedditTestInstance(
'test/user/lib_user_moderatorSubreddits.json');
final subreddits = <Subreddit>[];
await for (final subreddit in reddit.user.moderatorSubreddits()) {
subreddits.add(subreddit);
}
expect(subreddits.length, equals(1));
final subreddit = subreddits[0];
expect(subreddit.displayName, equals('drawapitesting'));
expect(subreddit.isContributor, isTrue);
expect(subreddit.isBanned, isFalse);
expect(subreddit.title, equals('DRAW API Testing'));
expect(subreddit.data!['public_description'],
contains('A subreddit used for testing'));
});
// TODO(bkonyi): update this test once Multireddit has been implemented.
test('lib/user/multireddits', () async {
final reddit =
await createRedditTestInstance('test/user/lib_user_multireddits.json');
final multis = (await reddit.user.multireddits()) as List<Multireddit>;
expect(multis.length, equals(1));
final multi = multis[0];
expect(multi.data!['name'], equals('drawtestingmulti'));
expect(multi.data!['display_name'], equals('drawtestingmulti'));
expect(multi.data!['can_edit'], isTrue);
expect(multi.data!['subreddits'].length, equals(81));
// TODO(bkonyi): once Multireddit is fully implemented, we probably want to
// return a map of [Subreddit]s.
expect(multi.data!['subreddits'][0]['name'], equals('lisp'));
});
test('lib/user/subreddits', () async {
final reddit =
await createRedditTestInstance('test/user/lib_user_subreddits.json');
final subs = <Subreddit>[];
await for (final subreddit in reddit.user.subreddits(limit: 101)) {
subs.add(subreddit);
}
expect(subs.length, equals(3));
// Note that there's only three subreddits returned here. These subreddits
// were subscribed to explicitly (r/announcements is a default, so it was
// unsubscribed from and resubscribed to) in order to be returned. In other
// words, default subreddits that the user is subscribed to will NOT be
// returned from this method unless resubscribed to.
expect(subs[0].displayName, equals('announcements'));
expect(subs[1].displayName, equals('dartlang'));
expect(subs[2].displayName, equals('drawapitesting'));
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/user_content_moderation/user_content_moderation_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> main() async {
test('lib/user_content_moderation/contest-mode', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_contest_mode.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.contestMode, false);
await submission.mod.contestMode();
await submission.refresh();
expect(submission.contestMode, true);
await submission.mod.contestMode(state: false);
await submission.refresh();
expect(submission.contestMode, false);
});
test('lib/user_content_moderation/set-flair', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_set_flair.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.data!['link_flair_text'], isNull);
await submission.mod.flair(text: 'Test Flair');
await submission.refresh();
expect(submission.data!['link_flair_text'], 'Test Flair');
await submission.mod.flair();
await submission.refresh();
expect(submission.data!['link_flair_text'], isNull);
});
test('lib/user_content_moderation/lock-unlock', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_lock_unlock.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.locked, isFalse);
await submission.mod.lock();
await submission.refresh();
expect(submission.locked, isTrue);
await submission.mod.unlock();
await submission.refresh();
expect(submission.locked, isFalse);
});
test('lib/user_content_moderation/nsfw-sfw', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_nsfw_sfw.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.over18, isFalse);
await submission.mod.nsfw();
await submission.refresh();
expect(submission.over18, isTrue);
await submission.mod.sfw();
await submission.refresh();
expect(submission.over18, isFalse);
});
test('lib/user_content_moderation/spoiler', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_spoiler.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.spoiler, isFalse);
await submission.mod.spoiler();
await submission.refresh();
expect(submission.spoiler, isTrue);
await submission.mod.unspoiler();
await submission.refresh();
expect(submission.spoiler, isFalse);
});
String _commentSortTypeToString(CommentSortType t) {
switch (t) {
case CommentSortType.confidence:
return 'confidence';
case CommentSortType.top:
return 'top';
case CommentSortType.newest:
return 'new';
case CommentSortType.controversial:
return 'controversial';
case CommentSortType.old:
return 'old';
case CommentSortType.random:
return 'random';
case CommentSortType.qa:
return 'qa';
case CommentSortType.blank:
return 'blank';
default:
throw DRAWInternalError('CommentSortType: $t is not supported.');
}
}
// TODO(bkonyi): add suggestedSort property to Submission
test('lib/user_content_moderation/suggested-sort', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_suggested_sort.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
for (final s in CommentSortType.values) {
await submission.mod.suggestedSort(sort: s);
await submission.refresh();
if (s != CommentSortType.blank) {
expect(submission.data!['suggested_sort'], _commentSortTypeToString(s));
} else {
expect(submission.data!['suggested_sort'], isNull);
}
}
expect(submission.data!['suggested_sort'], isNull);
}, skip: 'Needs updating to support "CommentSortType.best"');
test('lib/user_content_moderation/sticky', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_sticky.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.stickied, isFalse);
await submission.mod.sticky();
await submission.refresh();
expect(submission.stickied, isTrue);
await submission.mod.sticky(state: false);
await submission.refresh();
expect(submission.stickied, isFalse);
await submission.mod.sticky(bottom: false);
await submission.refresh();
expect(submission.stickied, isTrue);
await submission.mod.sticky(state: false);
await submission.refresh();
expect(submission.stickied, isFalse);
});
test('lib/user_content_moderation/remove-approve', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_remove_approve.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.removed, isFalse);
expect(submission.approved, isTrue);
await submission.mod.remove();
await submission.refresh();
expect(submission.removed, isTrue);
expect(submission.approved, isFalse);
await submission.mod.approve();
await submission.refresh();
expect(submission.removed, isFalse);
expect(submission.approved, isTrue);
});
test('lib/user_content_moderation/distinguish', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_distinguish.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.distinguished, null);
expect(submission.stickied, isFalse);
await submission.mod.distinguish(how: DistinctionType.yes);
await submission.refresh();
expect(submission.distinguished, 'moderator');
await submission.mod.undistinguish();
await submission.refresh();
expect(submission.distinguished, null);
expect(submission.stickied, isFalse);
});
test('lib/user_content_moderation/reports', () async {
final reddit = await createRedditTestInstance(
'test/user_content_moderation/lib_user_content_moderation_reports.json');
final submission = await reddit.submission(id: '7x6ew7').populate();
expect(submission.ignoreReports, isFalse);
await submission.mod.ignoreReports();
await submission.refresh();
expect(submission.ignoreReports, isTrue);
await submission.mod.unignoreReports();
await submission.refresh();
expect(submission.ignoreReports, isFalse);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/inbox/inbox_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> main() async {
test('lib/inbox/all', () async {
final reddit =
await createRedditTestInstance('test/inbox/lib_inbox_all.json');
final List<Message?> messages = <Message>[];
await for (final message in reddit.inbox.all()) {
messages.add(message);
}
expect(messages.length, equals(9));
expect(messages[0]!.author, equals('XtremeCheese'));
expect(messages[0]!.subject, equals('Test'));
expect(messages[0]!.body, equals('BLOCK ME I DARE YOU'));
});
test('lib/inbox/collapse_uncollapse', () async {
final reddit = await createRedditTestInstance(
'test/inbox/lib_inbox_collapse_uncollapse.json');
final message = await reddit.inbox.message('t4_awl3r7');
// There's no way to tell if a comment or message is collapsed, so we just
// exercise the API here as a sanity check.
await reddit.inbox.collapse([message]);
await reddit.inbox.uncollapse([message]);
});
test('lib/inbox/commentReplies', () async {
final reddit = await createRedditTestInstance(
'test/inbox/lib_inbox_comment_replies.json');
final comments = <Comment>[];
await for (final comment in reddit.inbox.commentReplies()) {
comments.add(comment);
}
expect(comments.length, equals(1));
final comment = comments[0];
expect(comment.author, equals('XtremeCheese'));
expect(comment.body, equals('Testing reply inbox'));
});
test('lib/inbox/markReadUnread', () async {
final reddit = await createRedditTestInstance(
'test/inbox/lib_inbox_mark_read_unread.json');
// We expect 1 unread comment.
var message = await reddit.inbox.unread().first as Comment;
expect(message.newItem, isTrue);
expect(message.author, equals('XtremeCheese'));
await reddit.inbox.markRead([message]);
// Check to make sure we have no unread messages in our inbox.
// ignore: unused_local_variable
await for (final message in reddit.inbox.unread()) {
// ignore: unused_local_variable
expect(true, isFalse);
}
// Mark the same messages as unread and check to make sure it was marked unread.
await reddit.inbox.markUnread([message]);
message = await reddit.inbox.unread().first as Comment;
expect(message.newItem, isTrue);
expect(message.author, equals('XtremeCheese'));
});
test('lib/inbox/mentions', () async {
final reddit =
await createRedditTestInstance('test/inbox/lib_inbox_mentions.json');
final comments = <Comment>[];
await for (final comment in reddit.inbox.mentions()) {
comments.add(comment);
}
expect(comments.length, equals(1));
final comment = comments[0];
expect(comment.subject, equals('username mention'));
expect(comment.author, equals('XtremeCheese'));
expect(comment.body, equals('/u/DRAWApiOfficial mention test'));
});
test('lib/inbox/message', () async {
final reddit =
await createRedditTestInstance('test/inbox/lib_inbox_message.json');
final message = (await reddit.inbox.message('t4_awl3r7')) as Message;
expect(message.id, equals('awl3r7'));
expect(message.body, equals('Hi!'));
expect(message.replies.length, equals(2));
});
test('lib/inbox/messages', () async {
final reddit =
await createRedditTestInstance('test/inbox/lib_inbox_messages.json');
final messages = <Message>[];
await for (final message in reddit.inbox.messages()) {
messages.add(message);
}
expect(messages.length, equals(14));
expect(messages[0].author, equals('XtremeCheese'));
expect(messages[0].subject, equals('Test'));
expect(messages[0].body, equals('BLOCK ME I DARE YOU'));
});
test('lib/inbox/sent', () async {
final reddit =
await createRedditTestInstance('test/inbox/lib_inbox_sent.json');
final messages = <Message>[];
await for (final message in reddit.inbox.sent()) {
messages.add(message);
}
expect(messages.length, equals(5));
final message = messages[0];
expect(message.author, equals('DRAWApiOfficial'));
expect(message.subject, equals('you are an approved submitter'));
});
test('lib/inbox/submissionReplies', () async {
final reddit = await createRedditTestInstance(
'test/inbox/lib_inbox_submission_replies.json');
final message = await reddit.inbox.submissionReplies().first;
expect(message.author, equals('XtremeCheese'));
expect(message.body, equals('Great talk!'));
expect(message.subject, equals('post reply'));
expect(message.wasComment, isTrue);
});
// TODO(bkonyi): implement
test('lib/inbox/uncollapse', () async {});
test('lib/inbox/unread', () async {
final reddit =
await createRedditTestInstance('test/inbox/lib_inbox_unread.json');
final message = await reddit.inbox.unread().first as Comment;
expect(message.author, equals('XtremeCheese'));
expect(message.body, equals('Great talk!'));
expect(message.subject, equals('post reply'));
expect(message.wasComment, isTrue);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/redditor/redditor_test.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> main() async {
test('lib/redditor/invalid_redditor', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_invalid.json');
await expectLater(
() async => await reddit.redditor('drawapiofficial2').populate(),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
test('lib/redditor/properties', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_properties.json');
final redditor = await reddit.redditor('DRAWApiOfficial').populate();
expect(redditor.commentKarma, 0);
expect(redditor.goldCreddits, 0);
expect(redditor.goldExpiration, isNull);
expect(redditor.hasGold, isFalse);
expect(redditor.hasModMail, isFalse);
expect(redditor.hasVerifiedEmail, isTrue);
expect(redditor.inBeta, isTrue);
expect(redditor.inboxCount, 7);
expect(redditor.isEmployee, isFalse);
expect(redditor.isModerator, isTrue);
expect(redditor.isSuspended, isFalse);
expect(redditor.linkKarma, 1);
expect(redditor.newModMailExists, isTrue);
expect(redditor.over18, isTrue);
expect(redditor.preferNoProfanity, isTrue);
expect(redditor.suspensionExpirationUtc, isNull);
});
test('lib/redditor/friend', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_friend.json');
final friendToBe = reddit.redditor('XtremeCheese');
await friendToBe.friend(note: 'My best friend!');
final myFriends = await reddit.user.friends();
expect(myFriends.length, equals(1));
final friend = myFriends[0];
expect(friend is Redditor, isTrue);
expect(friend.displayName, equals('XtremeCheese'));
expect(friend.note, equals('My best friend!'));
await friendToBe.unfriend();
final noFriends = await reddit.user.friends();
expect(noFriends.length, equals(0));
});
test('lib/redditor/bad_friend', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_bad_friend.json');
final badFriend = reddit.redditor('drawapiofficial2');
await expectLater(() async => await badFriend.friend(),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
test('lib/redditor/bad_unfriend', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_bad_unfriend.json');
final badFriend = reddit.redditor('drawapiofficial2');
await expectLater(() async => await badFriend.unfriend(),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
test('lib/redditor/bad_friend_info', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_bad_friend_info.json');
final badFriend = reddit.redditor('drawapiofficial2');
await expectLater(() async => await badFriend.friendInfo(),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
test('lib/redditor/bad_gild', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_bad_gild.json');
final badFriend = reddit.redditor('drawapiofficial2');
await expectLater(() async => await badFriend.gild(),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
test('lib/redditor/unblock', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_unblock.json');
var blockedUsers = await reddit.user.blocked();
expect(blockedUsers.length, equals(1));
// User was blocked before running this test.
final blocked = reddit.redditor('XtremeCheese');
await blocked.unblock();
blockedUsers = await reddit.user.blocked();
expect(blockedUsers.length, equals(0));
});
test('lib/redditor/invalid_unblock', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_invalid_unblock.json');
await expectLater(
() async => await reddit.redditor('drawapiofficial2').unblock(),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
// Note: tests for controversial, hot, newest, and top all use the same
// data for the different responses to save some effort.
test('lib/redditor/controversial', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_controversial.json');
final other = reddit.redditor('spez');
final posts = [];
await for (final post in other.controversial(params: {'limit': '2'})) {
expect(post is UserContent, isTrue);
posts.add(post);
}
final submission = posts[0];
final comment = posts[1];
expect(submission is Submission, isTrue);
expect(await submission.domain, equals('self.announcements'));
expect(await submission.id, equals('6qptzw'));
expect(comment is Comment, isTrue);
expect(await comment.id, equals('dkz2h82'));
expect(await comment.parentId, equals('t1_dkz1y5k'));
});
// Note: tests for controversial, hot, newest, and top all use the same
// data for the different responses to save some effort.
test('lib/redditor/hot', () async {
final reddit =
await createRedditTestInstance('test/redditor/lib_redditor_hot.json');
final other = reddit.redditor('spez');
final posts = [];
await for (final post in other.hot(params: {'limit': '2'})) {
expect(post is UserContent, isTrue);
posts.add(post);
}
final submission = posts[0];
final comment = posts[1];
expect(submission is Submission, isTrue);
expect(await submission.domain, equals('self.announcements'));
expect(await submission.id, equals('6qptzw'));
expect(comment is Comment, isTrue);
expect(await comment.id, equals('dkz2h82'));
expect(await comment.parentId, equals('t1_dkz1y5k'));
});
// Note: tests for controversial, hot, newest, and top all use the same
// data for the different responses to save some effort.
test('lib/redditor/newest', () async {
final reddit =
await createRedditTestInstance('test/redditor/lib_redditor_new.json');
final other = reddit.redditor('spez');
final posts = [];
await for (final post in other.newest(params: {'limit': '2'})) {
expect(post is UserContent, isTrue);
posts.add(post);
}
final submission = posts[0];
final comment = posts[1];
expect(submission is Submission, isTrue);
expect(await submission.domain, equals('self.announcements'));
expect(await submission.id, equals('6qptzw'));
expect(comment is Comment, isTrue);
expect(await comment.id, equals('dkz2h82'));
expect(await comment.parentId, equals('t1_dkz1y5k'));
});
// Note: tests for controversial, hot, newest, and top all use the same
// data for the different responses to save some effort.
test('lib/redditor/top', () async {
final reddit =
await createRedditTestInstance('test/redditor/lib_redditor_top.json');
final other = reddit.redditor('spez');
final posts = [];
await for (final post in other.top(params: {'limit': '2'})) {
expect(post is UserContent, isTrue);
posts.add(post);
}
final submission = posts[0];
final comment = posts[1];
expect(submission is Submission, isTrue);
expect(await submission.domain, equals('self.announcements'));
expect(await submission.id, equals('6qptzw'));
expect(comment is Comment, isTrue);
expect(await comment.id, equals('dkz2h82'));
expect(await comment.parentId, equals('t1_dkz1y5k'));
});
test('lib/redditor/gild', () async {
final reddit =
await createRedditTestInstance('test/redditor/lib_reddit_gild.json');
final other = await reddit.redditor('XtremeCheese').populate();
await other.gild();
});
test('lib/redditor/gild_insufficient_creddits', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_reddit_gild_insufficient.json');
final current = (await reddit.user.me()) as Redditor;
expect(current.goldCreddits, 0);
final other = await reddit.redditor('XtremeCheese').populate();
try {
await other.gild();
// ignore: unused_catch_clause
} on DRAWGildingException catch (e) {
// Success
} catch (e) {
rethrow;
}
});
test('lib/redditor/multireddits', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_multireddits.json');
final current = (await reddit.user.me()) as Redditor;
final multis = await current.multireddits();
expect(multis.length, 7);
expect(multis[0].displayName, 'all');
expect(multis[0].subreddits.length, 0);
});
test('lib/redditor/multireddits_bad_redditor', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_multireddits_bad_redditor.json');
await expectLater(
() async => await reddit.redditor('drawapiofficial2').multireddits(),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
test('lib/redditor/downvoted', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_reddit_downvoted.json');
final other = reddit.redditor('DRAWApiOfficial');
final content = [];
await for (final downvoted in other.downvoted(params: {'limit': '10'})) {
content.add(downvoted);
}
expect(content.length, equals(1));
expect(content[0] is Submission, isTrue);
expect(await content[0].domain, equals('self.announcements'));
expect(
await content[0].title,
equals('With so much going on in'
' the world, I thought I’d share some Reddit updates to distract '
'you all'));
expect(await content[0].author, equals('spez'));
});
test('lib/redditor/hidden', () async {
final reddit =
await createRedditTestInstance('test/redditor/lib_reddit_hidden.json');
final other = reddit.redditor('DRAWApiOfficial');
final content = [];
await for (final hidden in other.hidden(params: {'limit': '10'})) {
content.add(hidden);
}
expect(content.length, equals(1));
expect(content[0] is Submission, isTrue);
expect(await content[0].domain, equals('self.announcements'));
expect(await content[0].title, equals('Reddit\'s new signup experience'));
expect(await content[0].author, equals('simbawulf'));
});
test('lib/redditor/upvoted', () async {
final reddit =
await createRedditTestInstance('test/redditor/lib_reddit_upvoted.json');
final other = reddit.redditor('DRAWApiOfficial');
final content = [];
await for (final upvoted in other.upvoted(params: {'limit': '10'})) {
content.add(upvoted);
}
expect(content.length, equals(2));
expect(content[0] is Submission, isTrue);
expect(await content[0].domain, equals('github.com'));
expect(await content[0].title, equals('Official DRAW GitHub'));
expect(await content[0].author, equals('DRAWApiOfficial'));
expect(content[1] is Submission, isTrue);
expect(await content[1].domain, equals('self.drawapitesting'));
expect(
await content[1].title,
equals('test post please'
' ignore.'));
expect(await content[1].author, equals('DRAWApiOfficial'));
});
test('lib/redditor/comments_sanity', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_comments.json');
final redditor = reddit.redditor('DRAWApiOfficial');
final content = <Comment>[];
await for (final comment in redditor.comments.top(params: {'limit': '2'})) {
expect(comment is Comment, isTrue);
content.add(comment as Comment);
}
expect(content.length, 2);
expect(content[0].body, 'And this is a test comment!\n');
expect(content[1].body, 'Woohoo!');
});
test('lib/redditor/submissions_sanity', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_submissions.json');
final redditor = reddit.redditor('DRAWApiOfficial');
final content = <Submission>[];
await for (final submission
in redditor.submissions.newest(params: {'limit': '2'})) {
expect(submission is Submission, isTrue);
content.add(submission as Submission);
}
expect(content.length, 2);
expect(content[0].title,
'DRAW: Using Dart to Moderate Reddit Comments (DartConf 2018)');
expect(content[1].title, 'Tons of comments');
});
test('lib/redditor/saved_listing', () async {
final reddit =
await createRedditTestInstance('test/redditor/lib_redditor_saved.json');
final redditor = reddit.redditor('DRAWApiOfficial');
final content = <UserContent>[];
await for (final post in redditor.saved(params: {'limit': '2'})) {
content.add(post);
}
expect(content.length, 2);
expect(content[0] is Comment, isTrue);
expect((content[0] as Comment).body, "He gon' steal yo girl");
expect(content[1] is Submission, isTrue);
expect((content[1] as Submission).title, '😉');
});
test('lib/redditor/gildings', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_gildings.json');
final redditor = reddit.redditor('DRAWApiOfficial');
final content = <UserContent>[];
await for (final post in redditor.gildings(params: {'limit': '2'})) {
content.add(post);
}
expect(content.length, 1);
expect(content[0] is Submission, isTrue);
expect((content[0] as Submission).title, 'Gilded post!');
}, skip: 'Rewrite to handle new gilding types');
test('lib/redditor/trophies', () async {
final reddit = await createRedditTestInstance(
'test/redditor/lib_redditor_trophies.json');
final trophies = await reddit.redditor('spez').trophies();
expect(trophies, isNotEmpty);
final firstTrophy = trophies.first;
expect(firstTrophy.name, equals('13-Year Club'));
expect(firstTrophy.icon_70,
equals('https://www.redditstatic.com/awards2/13_year_club-70.png'));
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/auth/credentials.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:io';
final kApplicationClientID = Platform.environment['APP_CLIENT_ID'];
final kScriptClientID = Platform.environment['SCRIPT_CLIENT_ID'];
final kScriptClientSecret = Platform.environment['SCRIPT_CLIENT_SECRET'];
final kWebClientID = Platform.environment['WEB_CLIENT_ID'];
final kWebClientSecret = Platform.environment['WEB_CLIENT_SECRET'];
const kUsername = 'DRAWApiOfficial';
final kPassword = Platform.environment['PASSWORD'];
bool isScriptAuthConfigured =
(kScriptClientID != null) && (kScriptClientSecret != null);
bool isWebAuthConfigured = (kWebClientID != null) && (kWebClientSecret != null);
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/auth/web_auth.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import 'credentials.dart';
Future<void> main() async {
const cookieFile = 'cookie.txt';
const expectedState = 'foobar';
const headerFile = 'response.txt';
const redirect = 'https://www.google.com';
const scope = '*';
const userAgent = 'draw_web_test_agent';
test(
'web authenticator',
() async {
final reddit = Reddit.createWebFlowInstance(
clientId: kWebClientID,
clientSecret: kWebClientSecret,
redirectUri: Uri.parse(redirect),
userAgent: userAgent + '_authenticated');
expect(reddit.auth.userAgent, userAgent + '_authenticated');
// Create our code grant flow URI.
final dest = reddit.auth.url([scope], expectedState);
// ------------------------------------------------------------------ //
// Start Web Authentication Flow to Emulate User Granting Permissions //
// ------------------------------------------------------------------ //
// Login.
final loginResult = Process.runSync('curl', [
'-duser=$kUsername',
'-dpasswd=$kPassword',
'-dapi_type=json',
'-j',
'-A',
'"$userAgent"',
'-c$cookieFile',
'-v',
'https://ssl.reddit.com/api/login'
]);
final loginResponseMap = json.decode(loginResult.stdout);
final modhash = loginResponseMap['json']['data']['modhash'];
// Wait 2 seconds to avoid being rate limited (just in case).
await Future.delayed(Duration(seconds: 2));
// Accept permissions.
try {
// This sometimes throws with a FormatException: Bad UTF-8 encoding.
// Should probably hunt the cause down and file an issue...
Process.runSync('curl', [
'-L',
'--dump-header',
headerFile,
'-duh=$modhash',
'-dauthorize=Allow',
'-A',
'"$userAgent"',
'-c$cookieFile',
'-b$cookieFile',
Uri.decodeFull(dest.toString()),
]);
} catch (e) {
print('Exception caught: $e');
}
// The code is in the header of the response, which we've stored in
// response.txt.
final outputHeaderFile = File(headerFile);
expect(outputHeaderFile.existsSync(), isTrue);
final fileLines = outputHeaderFile.readAsStringSync().split('\n');
String? state;
String? code;
// Try and find the code and state in the response.
for (final line in fileLines) {
if (line.startsWith('location:')) {
final split = line.split(' ');
expect(split.length, 2);
final responseParams = Uri.parse(split[1]).queryParameters;
state = responseParams['state'];
code = responseParams['code'];
break;
}
}
// Check to see if we've found our code and state.
expect(state, isNotNull);
expect(state, expectedState);
expect(code, isNotNull);
if (code!.codeUnitAt(code.length - 1) == 13) {
// Remove \r (this was annoying to find).
code = code.substring(0, code.length - 1);
}
// ------------------------------------------------------------------ //
// End Web Authentication Flow to Emulate User Granting Permissions //
// ------------------------------------------------------------------ //
// Authorize via OAuth2.
await reddit.auth.authorize(code);
// Sanity check to ensure we have valid credentials.
expect(await reddit.user.me(), isNotNull);
final creds = reddit.auth.credentials.toJson();
// Attempt to create a new instance with the saved credentials.
final redditRestored = Reddit.restoreAuthenticatedInstance(creds,
clientId: kWebClientID,
clientSecret: kWebClientSecret,
userAgent: userAgent);
expect(await redditRestored.user.me(), isNotNull);
// Ensure we can refresh credentials.
await redditRestored.auth.refresh();
expect(await redditRestored.user.me(), isNotNull);
// Revoke the OAuth2 token and ensure an exception is thrown.
await redditRestored.auth.revoke();
// TODO(bkonyi): this check causes the test runner to hang. Investigate
// and file an issue against package:test if needed.
// expect(() async => await redditRestored.user.me(),
// throwsA(isInstanceOf<DRAWAuthenticationError>()));
},
// TODO(SupremeDeity): Still skipping due to FormatException
skip: 'https://github.com/draw-dev/DRAW/issues/209',
);
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/auth/read_only.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import 'credentials.dart';
Future<void> main() async {
test('read-only', () async {
final reddit = await Reddit.createReadOnlyInstance(
clientId: kScriptClientID,
clientSecret: kScriptClientSecret,
userAgent: 'readonly-client');
expect(reddit.readOnly, isTrue);
expect(await reddit.front.hot().first, isNotNull);
});
test('read-only untrusted', () async {
final reddit = await Reddit.createUntrustedReadOnlyInstance(
clientId: kApplicationClientID,
deviceId: 'DO_NOT_TRACK_THIS_DEVICE',
userAgent: 'readonly-client');
expect(reddit.readOnly, isTrue);
expect(await reddit.front.hot().first, isNotNull);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/auth/script_auth.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import 'credentials.dart';
Future<void> main() async {
test('script authenticator', () async {
if (kScriptClientSecret == null) return;
final reddit = await Reddit.createScriptInstance(
clientId: kScriptClientID,
clientSecret: kScriptClientSecret,
userAgent: 'script-client-DRAW-live-testing',
username: kUsername,
password: kPassword);
expect(reddit.readOnly, isFalse);
expect(await reddit.user.me(), isNotNull);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/auth/run_live_auth_tests.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'credentials.dart';
import 'read_only.dart' as read_only;
import 'script_auth.dart' as script;
import 'web_auth.dart' as web_auth;
void main() {
if (isScriptAuthConfigured) {
script.main();
read_only.main();
}
if (isWebAuthConfigured) {
web_auth.main();
}
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/gilded_listing_mixin/gilded_listing_mixin_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:draw/draw.dart';
import '../test_utils.dart';
Future<void> main() async {
test('lib/gilded_listing_mixin/front_page_gilded', () async {
final reddit = await createRedditTestInstance(
'test/gilded_listing_mixin/lib_gilded_listing_mixin_frontpage.json');
await for (final content in reddit.front.gilded(params: {'limit': '10'})) {
expect(content is UserContentInitialized, isTrue);
expect(content.silver >= 0, isTrue);
expect(content.gold >= 0, isTrue);
expect(content.platinum >= 0, isTrue);
}
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/subreddit/subreddit_test.dart | // Copyright (c) 2017, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
// ignore_for_file: unused_local_variable
Future<void> main() async {
test('lib/subreddit/invalid', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_invalid.json');
await expectLater(
() async => await reddit.subreddit('drawapitesting2').populate(),
throwsA(TypeMatcher<DRAWInvalidSubredditException>()));
});
test('lib/subreddit/banned', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_banned.json');
final subreddit = reddit.subreddit('drawapitesting');
await for (final user in subreddit.banned()) {
fail('Expected no returned values, got: $user');
}
await subreddit.banned.add('spez');
expect((await subreddit.banned().first).displayName, equals('spez'));
await subreddit.banned.remove('spez');
await for (final user in subreddit.banned()) {
fail('Expected no returned values, got: $user');
}
});
test('lib/subreddit/comment_stream', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_comments_stream.json');
var count = 0;
await for (final comment
in reddit.subreddit('drawapitesting').stream.comments(limit: 10)) {
expect(comment is CommentRef, isTrue);
count++;
}
expect(count, 10);
});
test('lib/subreddit/contributor', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_contributor.json');
final subreddit = reddit.subreddit('drawapitesting');
await subreddit.contributor.add('spez');
expect((await subreddit.contributor().first).displayName, equals('spez'));
await subreddit.contributor.remove('spez');
await for (final user in subreddit.contributor()) {
expect(user.displayName == 'spez', isFalse);
}
});
test('lib/subreddit/filter', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_filter.json');
final all = reddit.subreddit('all');
await all.filters.add('the_donald');
await for (final sub in all.filters()) {
expect(sub is SubredditRef, isTrue);
expect(sub.displayName.toLowerCase(), 'the_donald');
}
await all.filters.remove('the_donald');
await for (final sub in all.filters()) {
fail('There should be no subreddits being filtered, but $sub still is');
}
});
// Note: this test data is sanitized since it's garbage and I don't want that
// in my repo.
test('lib/subreddit/quarantine', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_quarantine.json');
final garbage = reddit.subreddit('whiteswinfights');
// Risky subreddit that's quarantined. In we go...
await garbage.quarantine.optIn();
try {
await for (final Submission submission
in garbage.top().cast<Submission>()) {
break;
}
} catch (e) {
fail('Got exception when we expected a submission. Exception: $e');
}
// Let's opt back out of seeing this subreddit...
await garbage.quarantine.optOut();
try {
await for (final Submission submission
in garbage.top().cast<Submission>()) {
fail('Expected DRAWAuthenticationError but got a submission');
}
} on DRAWAuthenticationError catch (e) {
// Phew, no more trash!
e.hashCode; // To get the analyzer to be quiet; does nothing.
} catch (e) {
fail('Expected DRAWAuthenticationError, got $e');
}
});
test('lib/subreddit/random', () async {
const randomTitle = 'A sentry slacking on the job';
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_random.json');
final subreddit = reddit.subreddit('tf2');
final submission = await (await subreddit.random()).populate();
expect(submission.title, equals(randomTitle));
});
test('lib/subreddit/rules', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_rules.json');
final subreddit = reddit.subreddit('whatcouldgowrong');
final rules = await subreddit.rules();
expect(rules.length, equals(5));
final ruleOne = rules[0];
expect(ruleOne.isLink, isTrue);
expect(ruleOne.description, '');
expect(
ruleOne.shortName,
equals('Contains stupid idea and thing going'
' wrong'));
expect(
ruleOne.violationReason,
equals('No stupid idea or Nothing went'
' wrong'));
expect(ruleOne.createdUtc, equals(1487830366.0));
expect(ruleOne.priority, equals(0));
});
test('lib/subreddit/sticky', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_sticky.json');
final subreddit = reddit.subreddit('drawapitesting');
final stickied = await (await subreddit.sticky()).populate();
expect(stickied.title, equals('Official DRAW GitHub'));
});
test('lib/subreddit/submit', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_submit.json');
final subreddit = reddit.subreddit('drawapitesting');
final originalSubmission = await subreddit.newest().first as Submission;
expect((originalSubmission.title == 'Testing3939057249'), isFalse);
await subreddit.submit('Testing3939057249', selftext: 'Hello Reddit!');
final submission = await subreddit.newest().first as Submission;
expect(submission.title, equals('Testing3939057249'));
expect(submission.selftext, equals('Hello Reddit!'));
});
test('lib/subreddit/subscribe_and_unsubscribe', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_subscribe_and_unsubscribe.json');
final subreddit = reddit.subreddit('funny');
await for (final subscription in reddit.user.subreddits()) {
expect(subscription.displayName == 'funny', isFalse);
expect(subscription.displayName == 'WTF', isFalse);
}
await subreddit
.subscribe(otherSubreddits: <SubredditRef>[reddit.subreddit('WTF')]);
// When running this live, Reddit seems to subscribe to the
// 'otherSubreddits' slightly after the single subreddit is being subscribed
// to. A short delay is enough to ensure Reddit finishes processing.
// await new Future.delayed(const Duration(seconds: 1));
var hasFunny = false;
var hasWTF = false;
await for (final subscription in reddit.user.subreddits()) {
if (subscription.displayName == 'WTF') {
hasWTF = true;
} else if (subscription.displayName == 'funny') {
hasFunny = true;
}
}
expect(hasFunny && hasWTF, isTrue);
await subreddit.unsubscribe(otherSubreddits: [reddit.subreddit('WTF')]);
// When running this live, Reddit seems to unsubscribe to the
// 'otherSubreddits' slightly after the single subreddit is being
// unsubscribed from. A short delay is enough to ensure Reddit finishes
// processing.
// await new Future.delayed(const Duration(seconds: 1));
await for (final subscription in reddit.user.subreddits()) {
expect(subscription.displayName == 'funny', isFalse);
expect(subscription.displayName == 'WTF', isFalse);
}
});
test('lib/subreddit/traffic', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_traffic.json');
final subreddit = reddit.subreddit('drawapitesting');
final traffic = await subreddit.traffic();
expect(traffic is Map<String, List<SubredditTraffic>>, isTrue);
expect(traffic.containsKey('day'), isTrue);
expect(traffic.containsKey('hour'), isTrue);
expect(traffic.containsKey('month'), isTrue);
final october = traffic['month'][0];
expect(october.uniques, equals(3));
expect(october.pageviews, equals(17));
expect(october.subscriptions, equals(0));
expect(october.periodStart, equals(DateTime.utc(2017, 10)));
});
test('lib/subreddit_stylesheet/call', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_call.json');
final subreddit = await reddit.subreddit('drawapitesting').populate();
final stylesheetHelper = subreddit.stylesheet;
final stylesheet = await stylesheetHelper();
expect(stylesheet, TypeMatcher<StyleSheet>());
expect(stylesheet.stylesheet,
'.flair-redandblue { color: blue; background: red; }');
expect(stylesheet.toString(), stylesheet.stylesheet);
expect(stylesheet.images.length, 1);
final dartLogo = stylesheet.images.first;
expect(
dartLogo.url,
Uri.parse(
'https://a.thumbs.redditmedia.com/firXjrOhN2odPDDkXWwvtIM1BttrTiZbPobp0MqO6b4.png'));
expect(dartLogo.link, 'url(%%dart-logo-400x400%%)');
expect(dartLogo.name, 'dart-logo-400x400');
expect(dartLogo.toString(), dartLogo.name);
});
test('lib/subreddit_stylesheet/delete_header', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_delete_header.json');
final subreddit = await reddit.subreddit('drawapitesting').populate();
expect(
subreddit.headerImage,
Uri.parse(
'https://b.thumbs.redditmedia.com/cXqC_cP8q0_exlq0HyaeW607ZIEU0o7yOSHnLnPUv-k.png'));
final stylesheet = subreddit.stylesheet;
await stylesheet.deleteHeader();
await subreddit.refresh();
expect(subreddit.headerImage, null);
});
test('lib/subreddit_stylesheet/delete_image', () async {
const kImageName = 'dart-logo-400x400';
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_delete_image.json');
final subreddit = await reddit.subreddit('drawapitesting').populate();
final stylesheet = subreddit.stylesheet;
var images = (await stylesheet()).images;
expect(images.length, 1);
expect(images.first.name, kImageName);
await stylesheet.deleteImage(kImageName);
images = (await stylesheet()).images;
expect(images.length, 0);
});
test('lib/subreddit_stylesheet/delete_mobile_header', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_delete_mobile_header.json');
final subreddit = await reddit.subreddit('drawapitesting').populate();
expect(
subreddit.mobileHeaderImage,
Uri.parse(
'https://b.thumbs.redditmedia.com/cXqC_cP8q0_exlq0HyaeW607ZIEU0o7yOSHnLnPUv-k.png'));
final stylesheet = subreddit.stylesheet;
await stylesheet.deleteMobileHeader();
await subreddit.refresh();
expect(subreddit.mobileHeaderImage, null);
});
test('lib/subreddit_stylesheet/delete_mobile_icon', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_delete_mobile_icon.json');
final subreddit = await reddit.subreddit('drawapitesting').populate();
final stylesheet = subreddit.stylesheet;
expect(
subreddit.iconImage,
Uri.parse(
'https://a.thumbs.redditmedia.com/4N-5XL7FZ6sA0WS7UpbdS1OSw9sGYHmNiIQ8SlFJ8b0.png'));
await stylesheet.deleteMobileIcon();
await subreddit.refresh();
expect(subreddit.iconImage, null);
});
test('lib/subreddit_stylesheet/update', () async {
const kNewStyle = '.flair-blueandred { color: red; background: blue; }';
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_update.json');
final subreddit = await reddit.subreddit('drawapitesting').populate();
final stylesheetHelper = subreddit.stylesheet;
var stylesheet = await stylesheetHelper();
expect(stylesheet.stylesheet,
'.flair-redandblue { color: blue; background: red; }');
await stylesheetHelper.update(kNewStyle, reason: 'Test');
stylesheet = await stylesheetHelper();
expect(stylesheet.stylesheet, kNewStyle);
});
test('lib/subreddit_stylesheet/upload', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_upload.json');
final stylesheet = reddit.subreddit('drawapitesting').stylesheet;
final uri = await stylesheet.upload('foobar',
format: ImageFormat.png,
imagePath: Uri.file('test/images/dart_header.png'));
expect(uri.toString(),
'https://a.thumbs.redditmedia.com/MJGdqUs7bXLgG7-pYG5zVRdI_6qUQ6svvlZXURe5K98.png');
});
test('lib/subreddit_stylesheet/upload_bytes', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_upload_bytes.json');
final stylesheet = reddit.subreddit('drawapitesting').stylesheet;
final imageBytes =
await File.fromUri(Uri.file('test/images/dart_header.png'))
.readAsBytes();
final uri = await stylesheet.upload('foobar',
bytes: imageBytes, format: ImageFormat.png);
expect(uri.toString(),
'https://a.thumbs.redditmedia.com/MJGdqUs7bXLgG7-pYG5zVRdI_6qUQ6svvlZXURe5K98.png');
});
test('lib/subreddit_stylesheet/upload_invalid_cases', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_upload_invalid_cases.json');
final stylesheet = reddit.subreddit('drawapitesting').stylesheet;
// Missing args.
await expectLater(
() async => await stylesheet.upload(
'foobar',
format: ImageFormat.png,
),
throwsA(TypeMatcher<DRAWArgumentError>()));
// Bad format.
await expectLater(
() async => await stylesheet.upload('foobar',
format: ImageFormat.jpeg,
imagePath: Uri.file('test/test_utils.dart')),
throwsA(TypeMatcher<DRAWImageUploadException>()));
// Too small.
await expectLater(
() async => await stylesheet.upload('foobar',
format: ImageFormat.jpeg,
imagePath: Uri.file('test/images/bad.jpg')),
throwsA(TypeMatcher<FormatException>()));
// File doesn't exist.
await expectLater(
() async => await stylesheet.upload('foobar',
format: ImageFormat.jpeg, imagePath: Uri.file('foobar.bad')),
throwsA(TypeMatcher<FileSystemException>()));
});
test('lib/subreddit_stylesheet/upload_header', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_upload_header.json');
final stylesheet = reddit.subreddit('drawapitesting').stylesheet;
final uri = await stylesheet.uploadHeader(
format: ImageFormat.png,
imagePath: Uri.file('test/images/dart_header.png'));
expect(uri.toString(),
'https://a.thumbs.redditmedia.com/MJGdqUs7bXLgG7-pYG5zVRdI_6qUQ6svvlZXURe5K98.png');
});
test('lib/subreddit_stylesheet/upload_mobile_header', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_upload_mobile_header.json');
final stylesheet = reddit.subreddit('drawapitesting').stylesheet;
final uri = await stylesheet.uploadMobileHeader(
format: ImageFormat.jpeg, imagePath: Uri.file('test/images/10by3.jpg'));
expect(uri.toString(),
'https://a.thumbs.redditmedia.com/MkErrkhg6-Iou7zdTRxnpwOSNK4DPWXZ3xI35LiKTU0.png');
});
test('lib/subreddit_stylesheet/upload_mobile_icon', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_stylesheet_upload_mobile_icon.json');
final stylesheet = reddit.subreddit('drawapitesting').stylesheet;
final uri = await stylesheet.uploadMobileIcon(
format: ImageFormat.png, imagePath: Uri.file('test/images/256.jpg'));
expect(uri.toString(),
'https://b.thumbs.redditmedia.com/GJSQRXiRY-2CH4PTgrrPNXqSPaQSKJYUikUr15m2n3Y.png');
});
test('lib/subreddit_flair/call', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_flair_call.json');
final subreddit = reddit.subreddit('drawapitesting');
final subredditFlair = subreddit.flair;
final flair = await subredditFlair().first;
expect(flair.user.displayName, 'DRAWApiOfficial');
expect(flair.flairCssClass, '');
expect(flair.flairText, 'Test Flair');
});
// TODO(bkonyi): Check that changes are sticking.
test('lib/subreddit_flair/configure', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_flair_configure.json');
final subreddit = await reddit.subreddit('drawapitesting').populate();
final subredditFlair = subreddit.flair;
await subredditFlair.configure(
linkPosition: FlairPosition.left,
position: FlairPosition.right,
linkSelfAssign: true,
selfAssign: true);
await subredditFlair.configure();
});
test('lib/subreddit_flair/setFlair', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_flair_set_flair.json');
final subreddit = reddit.subreddit('drawapitesting');
final subredditFlair = subreddit.flair;
final flairs = <Flair>[];
await for (final f in subredditFlair()) {
flairs.add(f);
}
expect(flairs.length, 1);
await subredditFlair.setFlair('XtremeCheese', text: 'Test flair 2');
flairs.clear();
await for (final f in subredditFlair()) {
flairs.add(f);
}
expect(flairs.length, 2);
});
test('lib/subreddit_flair/deleteAll', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_flair_delete_all.json');
final subreddit = reddit.subreddit('drawapitesting');
final subredditFlair = subreddit.flair;
final flairs = <Flair>[];
await for (final f in subredditFlair()) {
flairs.add(f);
}
expect(flairs.length, 1);
await subredditFlair.deleteAll();
flairs.clear();
await for (final f in subredditFlair()) {
flairs.add(f);
}
expect(flairs.length, 0);
});
test('lib/subreddit_flair/delete', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_flair_delete.json');
final subreddit = reddit.subreddit('drawapitesting');
final subredditFlair = subreddit.flair;
final flairs = <Flair>[];
await for (final f in subredditFlair()) {
flairs.add(f);
}
expect(flairs.length, 1);
await subredditFlair.delete('DRAWApiOfficial');
flairs.clear();
await for (final f in subredditFlair()) {
flairs.add(f);
}
expect(flairs.length, 0);
});
test('lib/subreddit_flair/update', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_flair_update.json');
final subreddit = reddit.subreddit('drawapitesting');
final subredditFlair = subreddit.flair;
final users = <String>['DRAWApiOfficial', 'XtremeCheese'];
await subredditFlair.update(users, text: 'Flair Test');
var count = 0;
await for (final f in subredditFlair()) {
expect(f.flairText, 'Flair Test');
++count;
}
expect(count, 2);
final redditors =
users.map<RedditorRef>((String user) => reddit.redditor(user)).toList();
await subredditFlair.update(redditors);
count = 0;
await for (final f in subredditFlair()) {
++count;
}
expect(count, 0);
});
test('lib/subreddit_flair/redditor_templates', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_flair_redditor_templates.json');
final subreddit = reddit.subreddit('drawapitesting');
final template = subreddit.flair.templates;
await template.add('Foobazbar', textEditable: true);
await template.add('Foobarz');
final list = <FlairTemplate>[];
await for (final t in template()) {
list.add(t);
}
expect(list.length, 2);
await template.delete(list[0].flairTemplateId);
list.clear();
await for (final t in template()) {
list.add(t);
}
expect(list.length, 1);
await template.update(list[0].flairTemplateId, 'Foo');
await template.clear();
await for (final t in template()) {
fail('Should not be any flair templates left');
}
});
test('lib/subreddit_flair/link_templates', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_flair_link_templates.json');
final subreddit = reddit.subreddit('drawapitesting');
final linkTemplate = subreddit.flair.linkTemplates;
await linkTemplate.add('Foobazbar', textEditable: true);
await linkTemplate.add('Foobarz');
final list = <FlairTemplate>[];
await for (final t in linkTemplate()) {
list.add(t);
}
expect(list.length, 2);
await linkTemplate.delete(list[0].flairTemplateId);
list.clear();
await for (final t in linkTemplate()) {
list.add(t);
}
expect(list.length, 1);
await linkTemplate.update(list[0].flairTemplateId, 'Foo');
await linkTemplate.clear();
await for (final t in linkTemplate()) {
fail('Should not be any link flair templates left');
}
});
test('lib/subreddit_wiki/create_wiki_page', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_create_wiki_page.json');
final wiki = reddit.subreddit('drawapitesting').wiki;
final page = await wiki.create('Test wiki page', 'This is a test page!');
expect(page.name, 'test_wiki_page');
expect(page.contentMarkdown, 'This is a test page!');
expect(page.contentHtml.contains('This is a test page!'), true);
expect(page.mayRevise, true);
expect(page.revisionBy.displayName, 'DRAWApiOfficial');
expect(page.revisionDate,
DateTime.fromMillisecondsSinceEpoch(1540940785 * 1000, isUtc: true));
});
test('lib/subreddit_wiki/invalid_wiki_page', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_invalid_wiki_page.json');
final wiki = reddit.subreddit('drawapitesting').wiki;
await expectLater(() async => await wiki['invalid'].populate(),
throwsA(TypeMatcher<DRAWNotFoundException>()));
});
test('lib/subreddit_wiki/edit_wiki_page', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_edit_wiki_page.json');
final wiki = reddit.subreddit('drawapitesting').wiki;
final page = await wiki['test_wiki_page'].populate();
expect(page.contentMarkdown, 'This is a test page!');
expect(page.revisionBy.displayName, 'DRAWApiOfficial');
expect(page.revisionDate,
DateTime.fromMillisecondsSinceEpoch(1540895666 * 1000, isUtc: true));
await page.edit('This is an edited test page!', reason: 'Test edit');
await page.refresh();
expect(page.contentMarkdown, 'This is an edited test page!');
expect(page.revisionBy.displayName, 'DRAWApiOfficial');
expect(page.revisionDate,
DateTime.fromMillisecondsSinceEpoch(1540896189 * 1000, isUtc: true));
});
test('lib/subreddit_wiki/wiki_equality', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_equality.json');
final wiki = reddit.subreddit('drawapitesting').wiki;
final pageRef = wiki['test_wiki_page'];
final page = await pageRef.populate();
final pageRef2 = wiki['test_page'];
final page2 = await pageRef2.populate();
expect(pageRef == page, true);
expect(pageRef == pageRef2, false);
expect(page == page2, false);
expect(page == pageRef2, false);
});
test('lib/subreddit_wiki/wiki_revisions', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_revisions.json');
final wiki = reddit.subreddit('drawapitesting').wiki;
final revisions = await wiki.revisions().toList();
expect(revisions.length, 5);
for (final r in revisions) {
expect(r.author.displayName, 'DRAWApiOfficial');
}
final last = revisions.last;
expect(last.page.name, 'test_page');
expect(last.reason, null);
expect(last.revision, '1445cccc-dbec-11e8-a780-0ef34ad82884');
expect(last.timestamp,
DateTime.fromMillisecondsSinceEpoch(1540895563 * 1000, isUtc: true));
expect(last == last, true);
expect(last.toString(), last.data.toString());
final lastRevisionPage =
await wiki['test_page'].revision(last.revision).populate();
expect(lastRevisionPage, last.page);
expect(lastRevisionPage.revisionDate, last.timestamp);
await lastRevisionPage.edit('Edited again!', reason: 'testing');
final newRevisions = await wiki.revisions().toList();
expect(newRevisions.length, 6);
final newRevision = newRevisions.first;
expect(newRevision.reason, 'testing');
expect(newRevision.revision, '091e41d0-dc5a-11e8-bdfa-0e7c30bc6e32');
expect(newRevision.timestamp,
DateTime.fromMillisecondsSinceEpoch(1540942789 * 1000, isUtc: true));
expect(last == newRevision, false);
final newRevisionPage =
await wiki['test_page'].revision(newRevision.revision).populate();
expect(newRevisionPage.contentMarkdown, 'Edited again!');
});
test('lib/subreddit_wiki/wiki_page_revisions', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_page_revisions.json');
final wikiPage =
await reddit.subreddit('drawapitesting').wiki['test_page'].populate();
final initial = await wikiPage.revisions().toList();
expect(initial.length, 27);
for (final edit in initial) {
expect(edit.page, wikiPage);
}
expect(initial.first.timestamp,
DateTime.fromMillisecondsSinceEpoch(1540942789 * 1000, isUtc: true));
await wikiPage.edit('New content');
final after = await wikiPage.revisions().toList();
expect(after.length, 28);
for (final edit in after) {
expect(edit.page, wikiPage);
}
expect(after.first.timestamp,
DateTime.fromMillisecondsSinceEpoch(1540981349 * 1000, isUtc: true));
});
test('lib/subreddit_wiki/wiki_page_moderation_add_remove', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_page_moderation_add_remove.json');
final wikiPage = reddit.subreddit('drawapitesting').wiki['test_page'];
final wikiPageMod = wikiPage.mod;
final settings = await wikiPageMod.settings();
expect(settings.editors.length, 0);
await wikiPageMod.add('Toxicity-Moderator');
await settings.refresh();
expect(settings.editors.length, 1);
expect(settings.editors[0].displayName, 'Toxicity-Moderator');
await wikiPageMod.remove(reddit.redditor('Toxicity-Moderator'));
await settings.refresh();
expect(settings.editors.length, 0);
});
test('lib/subreddit_wiki/wiki_page_moderation_invalid_add_remove', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_page_moderation_invalid_add_remove.json');
final wikiPage = reddit.subreddit('drawapitesting').wiki['test_page'];
final wikiPageMod = wikiPage.mod;
await expectLater(() async => await wikiPageMod.add('DrAwApIoFfIcIaL2'),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
await expectLater(() async => await wikiPageMod.remove('DrAwApIoFfIcIaL2'),
throwsA(TypeMatcher<DRAWInvalidRedditorException>()));
});
test('lib/subreddit_wiki/wiki_page_moderation_settings', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_wiki_page_moderation_settings.json');
final wikiPage = reddit.subreddit('drawapitesting').wiki['test_page'];
final wikiPageMod = wikiPage.mod;
final settings = await wikiPageMod.settings();
expect(
settings.permissionLevel, WikiPermissionLevel.approvedWikiContributors);
expect(settings.listed, true);
expect(settings.editors.length, 0);
final updated =
await wikiPageMod.update(false, WikiPermissionLevel.modsOnly);
expect(updated.permissionLevel, WikiPermissionLevel.modsOnly);
expect(updated.listed, false);
expect(updated.editors.length, 0);
});
test('lib/subreddit_wiki/WikiPermissionLevelOrdering', () {
expect(WikiPermissionLevel.values.length, 3);
expect(WikiPermissionLevel.values[0],
WikiPermissionLevel.useSubredditWikiPermissions);
expect(WikiPermissionLevel.values[1],
WikiPermissionLevel.approvedWikiContributors);
expect(WikiPermissionLevel.values[2], WikiPermissionLevel.modsOnly);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/subreddit/subreddits_test.dart | // Copyright (c) 2019, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:draw/src/models/subreddit.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
Future<void> main() async {
test('lib/subreddits/default', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddits_default.json');
final stream = reddit.subreddits.defaults(limit: 5);
final result = await stream.toList();
expect(result.length, 5);
});
test('lib/subreddits/gold', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddits_gold.json');
final stream = reddit.subreddits.gold(limit: 5);
final result = await stream.toList();
// Requires Reddit gold to get results.
expect(result.length, 0);
});
test('lib/subreddits/newest', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddits_newest.json');
final stream = reddit.subreddits.newest(limit: 5);
final result = await stream.toList();
expect(result.length, 5);
});
test('lib/subreddits/popular', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddits_popular.json');
final stream = reddit.subreddits.popular(limit: 5);
final result = await stream.toList();
expect(result.length, 5);
});
test('lib/subreddits/recommended', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddits_recommended.json');
final results = await reddit.subreddits.recommended(
['politics', SubredditRef.name(reddit, 'MorbidReality')],
omitSubreddits: ['hillaryclinton']);
expect(results.length, 10);
// ignore: unawaited_futures
expectLater(reddit.subreddits.recommended([2]),
throwsA(TypeMatcher<DRAWArgumentError>()));
});
test('lib/subreddits/search', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddits_search.json');
final results = await reddit.subreddits.search('drawapitesting').toList();
expect(results.length, 1);
});
test('lib/subreddits/search_by_name', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddits_search_by_name.json');
final names = (await reddit.subreddits.searchByName('Morbid'))
.map((s) => s.displayName);
final pattern = RegExp(r'[Mm]orbid');
for (final name in names) {
expect(name.startsWith(pattern), isTrue);
}
final sfw =
(await reddit.subreddits.searchByName('Morbid', includeNsfw: false));
for (final s in sfw) {
final populated = await s.populate();
expect(populated.over18, isFalse);
}
});
test('lib/subreddits/stream', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddits_stream.json');
final result = await reddit.subreddits.stream(limit: 1).toList();
expect(result.length, 1);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/subreddit/subreddit_moderation_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
import 'package:test/test.dart';
import '../test_utils.dart';
// ignore_for_file: unused_local_variable
late Reddit reddit;
Future<SubredditModeration> subredditModerationHelper(String path,
{live = false, sub = 'MorbidReality'}) async {
reddit = await createRedditTestInstance(path, live: live);
final subreddit = reddit.subreddit(sub);
return subreddit.mod;
}
Future<Modmail> subredditModmailHelper(String path,
{live = false, sub = 'MorbidReality'}) async {
reddit = await createRedditTestInstance(path, live: live);
final subreddit = reddit.subreddit(sub);
return subreddit.modmail;
}
Future<ModeratorRelationship> subredditModRelationshipHelper(String path,
{live = false, sub = 'drawapitesting'}) async {
reddit = await createRedditTestInstance(path, live: live);
final subreddit = reddit.subreddit(sub);
return subreddit.moderator;
}
Future<void> main() async {
test('lib/subreddit/subreddit_edited', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_moderation_edited.json');
// Retrieve recently edited `UserContent`.
await for (final post in morbidRealityMod.edited(limit: 5)) {
expect(post is UserContent, isTrue);
}
// Retrieve edited `Comment`s.
await for (final Comment post in morbidRealityMod
.edited(
limit: 5, only: SubredditModerationContentTypeFilter.commentsOnly)
.cast<Comment>()) {
expect(post.edited, isTrue);
expect(post.runtimeType, Comment);
}
// Retrieve edited `Submission`s. These are always self-text posts.
await for (final Submission post in morbidRealityMod
.edited(
limit: 5,
only: SubredditModerationContentTypeFilter.submissionsOnly)
.cast<Submission>()) {
expect(post.edited, isTrue);
// Only self-posts can be edited.
expect(post.isSelf, isTrue);
}
});
// TODO(bkonyi): make this test more verbose once `ModeratorAction` is
// fully implemented.
test('lib/subreddit/subreddit_mod_log', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_moderation_log.json');
// Retrieve the last mod action.
final modAction = await morbidRealityMod.log(limit: 1).first;
expect(modAction.subreddit, reddit.subreddit('MorbidReality'));
expect(modAction.action, ModeratorActionType.removeComment);
final cheese =
await morbidRealityMod.log(limit: 1, mod: 'XtremeCheese').first;
expect(cheese.mod.displayName, 'XtremeCheese');
expect(cheese.action, ModeratorActionType.approveComment);
final redditor =
await morbidRealityMod.log(mod: reddit.redditor('XtremeCheese')).first;
expect(redditor.mod.displayName, 'XtremeCheese');
final redditorsList = <RedditorRef>[];
redditorsList.add(reddit.redditor('XtremeCheese'));
redditorsList.add(reddit.redditor('spez'));
final redditors =
await morbidRealityMod.log(mod: redditorsList, limit: 5).first;
expect(redditors.mod.displayName, 'XtremeCheese');
try {
final wiki = await morbidRealityMod
.log(
mod: reddit.redditor('XtremeCheese'),
type: ModeratorActionType.wikiUnbanned,
limit: 1)
.first;
} on StateError catch (e) {
// Keep the analyzer quiet.
expect(e is StateError, isTrue);
} catch (e) {
fail("Expected 'StateError' to be throw, got '$e'");
}
expect(redditors.toString(), isNotNull);
});
test('lib/subreddit/subreddit_mod_queue', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_mod_queue.json');
// Retrieve recently posted `UserContent`.
final post = (await morbidRealityMod.modQueue().first) as Comment;
expect(
post.body, "If the toddler had a gun this wouldn't have happened /s");
// Retrieve recently posted `Comment`s.
await for (final post in morbidRealityMod.modQueue(
limit: 5, only: SubredditModerationContentTypeFilter.commentsOnly)) {
expect(post.runtimeType, Comment);
}
// Retrieve recently posted `Submission`s.
await for (final post in morbidRealityMod.modQueue(
limit: 5, only: SubredditModerationContentTypeFilter.submissionsOnly)) {
expect(post.runtimeType, Submission);
}
});
test('lib/subreddit/subreddit_reports', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_mod_reports.json');
// Retrieve recently posted `UserContent`.
final post = (await morbidRealityMod.reports().first) as Comment;
expect(post.modReports.length, 0);
expect(post.userReports.length, 1);
final userReport = post.userReports[0];
expect(userReport[0], 'Rule #1 - tasteless humor');
expect(userReport[1], 1);
// Retrieve recently reported `Comment`s.
await for (final post in morbidRealityMod.modQueue(
limit: 5, only: SubredditModerationContentTypeFilter.commentsOnly)) {
expect(post.runtimeType, Comment);
}
// Retrieve recently reported `Submission`s.
await for (final post in morbidRealityMod.modQueue(
limit: 5, only: SubredditModerationContentTypeFilter.submissionsOnly)) {
expect(post.runtimeType, Submission);
}
});
test('lib/subreddit/subreddit_spam', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_mod_spam.json');
// Retrieve recently posted `UserContent`.
final post = (await morbidRealityMod.spam().first) as Comment;
// Items in the spam queue aren't necessarily marked as spam.
expect(post.spam, isFalse);
// Nothing that can really be checked here to verify the items are in the
// spam queue, so we'll just exercise the filters.
await for (final Comment post in morbidRealityMod
.spam(limit: 5, only: SubredditModerationContentTypeFilter.commentsOnly)
.cast<Comment>()) {}
await for (final Submission post in morbidRealityMod
.spam(
limit: 5,
only: SubredditModerationContentTypeFilter.submissionsOnly)
.cast<Submission>()) {}
});
test('lib/subreddit/subreddit_unmoderated', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_mod_unmoderated.json');
// Retrieve unmoderated `UserContent`.
final post = await morbidRealityMod.unmoderated().first;
expect(post is UserContent, isTrue);
// In this case, we know we're getting a submission back, but that's not
// always the case.
final submission = post as Submission;
// Unmoderated posts are never approved.
expect(submission.approved, isFalse);
});
test('lib/subreddit/subreddit_inbox', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_moderation_inbox.json');
final messages = <Message>[];
await for (final message in morbidRealityMod.inbox(limit: 2)) {
messages.add(message);
}
expect(messages.length, 2);
// We'll just check the first message's content.
final message = messages[0];
expect(message.author, 'GoreFox');
expect(message.destination, 'bluntmanandrobin');
expect(message.subject, "you've been banned");
expect(message.body, contains('you have been banned from posting to'));
expect(message.replies.length, 10);
});
test('lib/subreddit/subreddit_mod_unread', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_moderation_unread.json');
final message = await morbidRealityMod.unread().first;
// Obviously, this message should be new.
expect(message.newItem, isTrue);
expect(message.author, 'AutoModerator');
expect(message.subject, 'Doxxing Alert!');
expect(message.subreddit!.displayName, 'MorbidReality');
});
test('lib/subreddit/subreddit_settings', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_moderation_settings.json');
final settings = await morbidRealityMod.settings();
expect(settings.allowPostCrossposts, isTrue);
expect(settings.defaultSet, isTrue);
expect(settings.description, isNotNull);
expect(settings.publicDescription, isNotNull);
expect(settings.subredditType, SubredditType.publicSubreddit);
expect(settings.commentScoreHideMins, 60);
expect(settings.showMediaPreview, isTrue);
expect(settings.allowImages, isTrue);
expect(settings.allowFreeformReports, isTrue);
expect(settings.wikiEditAge, 365);
expect(settings.submitText, '');
expect(settings.title, 'The darkest recesses of humanity');
expect(settings.collapseDeletedComments, isTrue);
expect(settings.publicTraffic, isFalse);
expect(settings.over18, isTrue);
expect(settings.allowVideos, isFalse);
expect(settings.spoilersEnabled, isFalse);
expect(settings.submitLinkLabel, 'Submit');
expect(settings.submitTextLabel, isNull);
expect(settings.language, 'en');
expect(settings.wikiEditKarma, 1000);
expect(settings.hideAds, isFalse);
expect(settings.headerHoverText, 'MorbidReality');
expect(settings.allowDiscovery, isTrue);
expect(settings.showMediaPreview, isTrue);
expect(settings.commentScoreHideMins, 60);
expect(settings.excludeBannedModQueue, isTrue);
expect(settings.toString(), isNotNull);
});
test('lib/subreddit/subreddit_settings_local_modify', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_moderation_settings.json');
final settings = await morbidRealityMod.settings();
expect(settings.allowPostCrossposts, isTrue);
settings.allowPostCrossposts = false;
expect(settings.allowPostCrossposts, isFalse);
expect(settings.showMedia, isTrue);
settings.showMedia = false;
expect(settings.showMedia, isFalse);
expect(settings.defaultSet, isTrue);
settings.defaultSet = false;
expect(settings.defaultSet, isFalse);
expect(settings.description, isNotNull);
settings.description = null;
expect(settings.description, isNull);
expect(settings.publicDescription, isNotNull);
settings.publicDescription = null;
expect(settings.publicDescription, isNull);
expect(settings.subredditType, SubredditType.publicSubreddit);
settings.subredditType = SubredditType.restrictedSubreddit;
expect(settings.subredditType, SubredditType.restrictedSubreddit);
expect(settings.commentScoreHideMins, 60);
settings.commentScoreHideMins = 30;
expect(settings.commentScoreHideMins, 30);
expect(settings.showMediaPreview, isTrue);
settings.showMediaPreview = false;
expect(settings.showMediaPreview, isFalse);
expect(settings.allowImages, isTrue);
settings.allowImages = false;
expect(settings.allowImages, isFalse);
expect(settings.allowFreeformReports, isTrue);
settings.allowFreeformReports = false;
expect(settings.allowFreeformReports, isFalse);
expect(settings.wikiEditAge, 365);
settings.wikiEditAge = 10;
expect(settings.wikiEditAge, 10);
expect(settings.submitText, '');
settings.submitText = 'foobar';
expect(settings.submitText, 'foobar');
expect(settings.title, 'The darkest recesses of humanity');
settings.title = 'testing';
expect(settings.title, 'testing');
expect(settings.collapseDeletedComments, isTrue);
settings.collapseDeletedComments = false;
expect(settings.collapseDeletedComments, isFalse);
expect(settings.publicTraffic, isFalse);
settings.publicTraffic = true;
expect(settings.publicTraffic, isTrue);
expect(settings.over18, isTrue);
settings.over18 = false;
expect(settings.over18, isFalse);
expect(settings.allowVideos, isFalse);
settings.allowVideos = true;
expect(settings.allowVideos, isTrue);
expect(settings.spoilersEnabled, isFalse);
settings.spoilersEnabled = true;
expect(settings.spoilersEnabled, isTrue);
expect(settings.submitLinkLabel, 'Submit');
settings.submitLinkLabel = 'Post';
expect(settings.submitLinkLabel, 'Post');
expect(settings.submitTextLabel, isNull);
settings.submitTextLabel = 'foobar';
expect(settings.submitTextLabel, 'foobar');
expect(settings.language, 'en');
settings.language = 'de';
expect(settings.language, 'de');
expect(settings.wikiEditKarma, 1000);
settings.wikiEditKarma = 10;
expect(settings.wikiEditKarma, 10);
expect(settings.hideAds, isFalse);
settings.hideAds = true;
expect(settings.hideAds, isTrue);
expect(settings.headerHoverText, 'MorbidReality');
settings.headerHoverText = 'foobar';
expect(settings.headerHoverText, 'foobar');
expect(settings.allowDiscovery, isTrue);
settings.allowDiscovery = false;
expect(settings.allowDiscovery, isFalse);
expect(settings.excludeBannedModQueue, isTrue);
settings.excludeBannedModQueue = false;
expect(settings.excludeBannedModQueue, isFalse);
expect(settings.toString(), isNotNull);
});
test('lib/subreddit/subreddit_settings_copy', () async {
final morbidRealityMod = await subredditModerationHelper(
'test/subreddit/subreddit_moderation_settings.json');
final settings = await morbidRealityMod.settings();
final settingsCopy = SubredditSettings.copy(settings);
expect(settings.allowPostCrossposts, settingsCopy.allowPostCrossposts);
expect(settings.defaultSet, settingsCopy.defaultSet);
expect(settings.description, settingsCopy.description);
expect(settings.publicDescription, settingsCopy.publicDescription);
expect(settings.subredditType, settingsCopy.subredditType);
expect(settings.commentScoreHideMins, settingsCopy.commentScoreHideMins);
expect(settings.showMediaPreview, settingsCopy.showMediaPreview);
expect(settings.allowImages, settingsCopy.allowImages);
expect(settings.allowFreeformReports, settingsCopy.allowFreeformReports);
expect(settings.wikiEditAge, settingsCopy.wikiEditAge);
expect(settings.submitText, settingsCopy.submitText);
expect(settings.title, settingsCopy.title);
expect(
settings.collapseDeletedComments, settingsCopy.collapseDeletedComments);
expect(settings.publicTraffic, settingsCopy.publicTraffic);
expect(settings.over18, settingsCopy.over18);
expect(settings.allowVideos, settingsCopy.allowVideos);
expect(settings.spoilersEnabled, settingsCopy.spoilersEnabled);
expect(settings.submitLinkLabel, settingsCopy.submitLinkLabel);
expect(settings.submitTextLabel, settingsCopy.submitTextLabel);
expect(settings.language, settingsCopy.language);
expect(settings.wikiEditKarma, settingsCopy.wikiEditKarma);
expect(settings.hideAds, settingsCopy.hideAds);
expect(settings.headerHoverText, settingsCopy.headerHoverText);
expect(settings.allowDiscovery, settingsCopy.allowDiscovery);
expect(settings.showMediaPreview, settingsCopy.showMediaPreview);
expect(settings.commentScoreHideMins, settingsCopy.commentScoreHideMins);
expect(settings.excludeBannedModQueue, settingsCopy.excludeBannedModQueue);
expect(settings.toString(), settingsCopy.toString());
});
test('lib/subreddit/subreddit_update_settings', () async {
final drawApiTestingMod = await subredditModerationHelper(
'test/subreddit/subreddit_update_settings.json',
sub: 'drawapitesting');
var settings = await drawApiTestingMod.settings();
expect(settings.title, 'DRAW API Testing');
final originalTitle = settings.title;
settings.title = 'test title';
await drawApiTestingMod.update(settings);
final newSettings = await drawApiTestingMod.settings();
expect(newSettings.title, settings.title);
newSettings.title = originalTitle;
await drawApiTestingMod.update(newSettings);
settings = await drawApiTestingMod.settings();
expect(settings.title, 'DRAW API Testing');
});
test('lib/subreddit/subreddit_modmail_bulkread', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_bulkread.json',
sub: 'drawapitesting');
final conversation =
await ModmailConversationRef(reddit, '3nyfr').populate();
await conversation.unread();
final oneMarkedRead = await modmail.bulkRead();
expect(oneMarkedRead.length, 1);
expect(oneMarkedRead[0].id, '3nyfr');
final nonMarkedRead = await modmail.bulkRead();
expect(nonMarkedRead.isEmpty, true);
});
test('lib/subreddit/subreddit_modmail_conversations', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_conversation.json',
sub: 'drawapitesting');
final conversations = <ModmailConversation>[];
await for (final c in modmail.conversations()) {
conversations.add(c);
}
expect(conversations.length, 7);
final c = conversations[0];
expect(c.lastUserUpdate, null);
expect(c.isInternal, false);
expect(c.isHighlighted, true);
expect(c.subject, 'Test message');
expect(c.lastModUpdate, DateTime.parse('2018-04-27T23:29:57.985942+00:00'));
expect(c.lastUpdated, DateTime.parse('2018-04-27T23:29:57.985942+00:00'));
expect(c.authors.length, 1);
expect(c.authors[0].isModerator, true);
expect(c.authors[0].displayName, 'DRAWApiOfficial');
expect(c.owner.displayName, 'drawapitesting');
expect(c.participant.displayName, 'Toxicity-Moderator');
expect(c.numMessages, 1);
expect(c.messages.length, c.numMessages);
expect(c.messages[0].bodyMarkdown, 'Hello Toxicity-Moderator!');
});
test('lib/subreddit/subreddit_modmail_create', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_create.json',
sub: 'drawapitesting');
final message = await modmail.create(
'Test Message!', 'Hello Reddit!', 'DRAWApiOfficial',
authorHidden: true);
expect(message.authors.length, 1);
expect(message.subject, 'Test Message!');
expect(message.isInternal, true);
expect(message.numMessages, 1);
});
test('lib/subreddit/subreddit_modmail_subreddits', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_subreddits.json',
sub: 'drawapitesting');
await for (final sub in modmail.subreddits()) {
expect(sub.displayName, 'drawapitesting');
}
});
test('lib/subreddit/subreddit_modmail_unread_count', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_unread_count.json',
sub: 'drawapitesting');
final read = await modmail.unreadCount();
expect(read.archived, 0);
expect(read.highlighted, 0);
expect(read.inProgress, 0);
expect(read.mod, 0);
expect(read.newMail, 0);
expect(read.notifications, 0);
final conversation =
await ModmailConversationRef(reddit, '3nyfr').populate();
await conversation.unread();
final unread = await modmail.unreadCount();
expect(unread.archived, 0);
expect(unread.highlighted, 0);
expect(unread.inProgress, 1);
expect(unread.mod, 0);
expect(unread.newMail, 0);
expect(unread.notifications, 0);
await conversation.read();
});
test('lib/subreddit/subreddit_modmail_archive_unarchive', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_archive_unarchive.json',
sub: 'drawapitesting');
final conversation = (await ModmailConversation(reddit, id: '3nyfr')
.refresh()) as ModmailConversation;
// TODO(bkonyi): figure out how to determine whether or not a conversation is archived.
// Manually confirmed this works for now.
expect(conversation.isHighlighted, false);
await conversation.archive();
expect(conversation.isHighlighted, false);
await conversation.unarchive();
expect(conversation.isHighlighted, false);
});
test('lib/subreddit/subreddit_modmail_highlight_unhighlight', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_highlight_unhighlight.json',
sub: 'drawapitesting');
final conversation = (await ModmailConversation(reddit, id: '3nyfr')
.refresh()) as ModmailConversation;
expect(conversation.isHighlighted, false);
await conversation.highlight();
expect(conversation.isHighlighted, true);
await conversation.unhighlight();
expect(conversation.isHighlighted, false);
});
test('lib/subreddit/subreddit_modmail_mute_unmute', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_mute_unmute.json',
sub: 'drawapitesting');
final conversation = (await ModmailConversation(reddit, id: '3nyfr')
.refresh()) as ModmailConversation;
// TODO(bkonyi): figure out how to determine whether or not a conversation is muted.
// Manually confirmed this works for now.
expect(conversation.isHighlighted, false);
await conversation.mute();
expect(conversation.isHighlighted, false);
await conversation.unmute();
expect(conversation.isHighlighted, false);
});
test('lib/subreddit/subreddit_modmail_read_unread', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_read_unread.json',
sub: 'drawapitesting');
final convos = <ModmailConversation>[];
await for (final c in modmail.conversations(limit: 5)) {
convos.add(c);
}
// TODO(bkonyi): figure out how to determine whether or not a conversation is read.
// Manually confirmed this works for now.
final first = convos.first;
final rest = convos.sublist(1);
await first.read(otherConversations: rest);
await first.unread(otherConversations: rest);
await first.read(otherConversations: rest);
});
test('lib/subreddit/subreddit_modmail_reply', () async {
final modmail = await subredditModmailHelper(
'test/subreddit/subreddit_modmail_reply.json',
sub: 'drawapitesting');
final conversation = await modmail('3nyfr').populate();
final internal = await conversation.reply('TestInternal',
authorHidden: true, internal: true);
expect(internal.isInternal, true);
expect(internal.isHidden, true);
expect(internal.author.displayName, 'DRAWApiOfficial');
expect(internal.bodyMarkdown, 'TestInternal');
final hidden = await conversation.reply('Test hidden', authorHidden: true);
expect(hidden.isInternal, false);
expect(hidden.isHidden, true);
expect(hidden.isOriginalPoster, true);
expect(hidden.isDeleted, false);
expect(hidden.author.displayName, 'DRAWApiOfficial');
expect(hidden.isParticipant, false);
expect(hidden.bodyMarkdown, 'Test hidden');
final reply = await conversation.reply('Visible reply');
expect(reply.isInternal, false);
expect(reply.isHidden, false);
expect(reply.isOriginalPoster, true);
expect(reply.isParticipant, false);
expect(reply.isDeleted, false);
expect(reply.author.isModerator, true);
expect(reply.body,
'<!-- SC_OFF --><div class=\"md\"><p>Visible reply</p>\n</div><!-- SC_ON -->');
expect(reply.bodyMarkdown, 'Visible reply');
expect(reply.date, DateTime.parse('2018-10-06 22:56:49.916324Z'));
expect(reply.toString() != '', true);
final action = conversation.modActions[0];
expect(action.actionType, ModmailActionType.highlight);
expect(action.date, DateTime.parse('2018-09-29T19:35:25.916654+00:00'));
expect(action.id, '37g4f');
expect(action.author.displayName, 'DRAWApiOfficial');
});
test('lib/subreddit/moderator_relationship_mods', () async {
final relationship = await subredditModRelationshipHelper(
'test/subreddit/lib_subreddit_moderator_relationship_mods.json');
final mods = await relationship().toList();
expect(mods.length, 2);
expect(mods[0].displayName, 'XtremeCheese');
expect(mods[1].displayName, 'DRAWApiOfficial');
final cheese = await relationship(redditor: 'XtremeCheese').toList();
expect(cheese.length, 1);
expect(cheese[0].displayName, 'XtremeCheese');
expect(cheese[0].moderatorPermissions[0], ModeratorPermission.all);
});
test('lib/subreddit/moderator_relationship_add_invite', () async {
final relationship = await subredditModRelationshipHelper(
'test/subreddit/lib_subreddit_moderator_relationship_add_invite.json');
await relationship
.add('Toxicity-Moderator', permissions: [ModeratorPermission.all]);
await relationship
.invite('Toxicity-Moderator', permissions: [ModeratorPermission.all]);
await relationship.updateInvite('Toxicity-Moderator');
await relationship.removeInvite('Toxicity-Moderator');
});
test('lib/subreddit/moderator_relationship_leave', () async {
final relationship = await subredditModRelationshipHelper(
'test/subreddit/lib_subreddit_moderator_relationship_leave.json');
var mods = await relationship().toList();
var containsDRAWApiOfficial = false;
for (final m in mods) {
if (m.displayName == 'DRAWApiOfficial') {
containsDRAWApiOfficial = true;
break;
}
}
expect(containsDRAWApiOfficial, true);
await relationship.leave();
containsDRAWApiOfficial = false;
mods = await relationship().toList();
for (final m in mods) {
if (m.displayName == 'DRAWApiOfficial') {
containsDRAWApiOfficial = true;
break;
}
}
expect(containsDRAWApiOfficial, false);
});
test('lib/subreddit/moderator_relationship_remove', () async {
final relationship = await subredditModRelationshipHelper(
'test/subreddit/lib_subreddit_moderator_relationship_remove.json');
var mods = await relationship().toList();
var containsCheese = false;
for (final m in mods) {
if (m.displayName == 'XtremeCheese') {
containsCheese = true;
break;
}
}
expect(containsCheese, true);
await relationship.remove('XtremeCheese');
containsCheese = false;
mods = await relationship().toList();
for (final m in mods) {
if (m.displayName == 'XtremeCheese') {
containsCheese = true;
break;
}
}
expect(containsCheese, false);
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/subreddit/subreddit_listing_mixin_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:draw/draw.dart';
import '../test_utils.dart';
Future<void> main() async {
test('lib/subreddit/subreddit_listing_mixin_sanity', () async {
final reddit = await createRedditTestInstance(
'test/subreddit/lib_subreddit_listing_mixin_sanity.json');
final subreddit = reddit.subreddit('funny');
await for (final content in subreddit.comments(params: {'limit': '10'})) {
expect(content is Comment, isTrue);
expect(content.body, isNotNull);
}
});
}
| 0 |
mirrored_repositories/DRAW/test | mirrored_repositories/DRAW/test/rising_listing_mixin/rising_listing_mixin_test.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:draw/draw.dart';
import '../test_utils.dart';
Future<void> main() async {
test('lib/rising_listing_mixin/random_rising_sanity', () async {
final reddit = await createRedditTestInstance(
'test/rising_listing_mixin/lib_rising_listing_mixin_random_rising.json');
await for (final rand
in reddit.front.randomRising(params: {'limit': '10'})) {
expect(rand is Submission, isTrue);
}
});
test('lib/rising_listing_mixin/rising_sanity', () async {
final reddit = await createRedditTestInstance(
'test/rising_listing_mixin/lib_rising_listing_mixin_rising.json');
await for (final rise in reddit.front.rising(params: {'limit': '10'})) {
expect(rise is Submission, isTrue);
}
});
}
| 0 |
mirrored_repositories/DRAW/third_party/reply | mirrored_repositories/DRAW/third_party/reply/lib/reply.dart | /// Utilities for recording and replaying API interactions.
///
/// Reply is a general use library that can:
/// - Allow programmatic configuration (i.e. stubbing/mocking)
/// - Serve as a more complex state machine
/// - Reusable as a record/replay infrastructure for e2e testing
library reply;
import 'package:collection/collection.dart';
part 'src/conclusion_builder.dart';
part 'src/recorder.dart';
part 'src/recording.dart';
part 'src/response_builder.dart';
/// A configured `request->response` pair.
abstract class Record<Q, R> {
/// Whether this response should never be removed (always respond).
bool get always;
/// When to respond.
Q get request;
/// What to respond with.
R get response;
}
/// Builds pairs of request/response(s).
///
/// Use a recorder to fluently write configuration:
/// recorder
/// .given('Hello')
/// .reply('Hi there!')
/// .record();
///
/// A recorder can be converted to a [Recording] to play back:
/// recorder.toRecording().reply('Hello') // Returns 'Hi there!'
abstract class Recorder<Q, R> {
/// Create a new empty [Recorder].
///
/// Optionally specify how request object [Q] should be identified.
factory Recorder({
/// Optionally specify how a request [Q] should be considered equal.
Equality<Q>? requestEquality,
}) =>
_DefaultRecorder<Q, R>(requestEquality: requestEquality);
/// Adds a configured [record].
///
/// Most user implementations should use the [given] builder. This is provided
/// mostly to allow extensibility/custom recorders in the near future.
void addRecord(Record<Q, R> record);
/// Returns a builder that configures what to do when [request] is received.
///
/// If [request] already exists, the response is queued as a future response.
ResponseBuilder<Q, R> given(Q request);
/// Returns a collection of all recorded request/response pairs.
Recording<Q, R> toRecording();
}
abstract class Recording<Q, R> {
/// Create a new set of [records].
///
/// Optionally specify how a request [Q] should be considered equal.
factory Recording(
Iterable<Record<Q, R>> records, {
Equality<Q>? requestEquality,
}) =>
_DefaultRecording(records, requestEquality: requestEquality);
/// Return a new set of records by decoding JSON [data].
factory Recording.fromJson(
Iterable<Map<String, dynamic>> data, {
required Q Function(dynamic request) toRequest,
required R Function(dynamic response) toResponse,
Equality<Q>? requestEquality,
}) {
return Recording(
data.map((r) => _DefaultRecord(
toRequest(r['request']),
toResponse(r['response']),
always: r['always'] == true,
)),
requestEquality: requestEquality,
);
}
/// Returns whether [request] is recorded.
bool hasRecord(Q request);
/// Resolves and returns a response for [request].
///
/// If not found throws [StateError].
R reply(Q request);
/// Returns a JSON serializable object from this set of recordings.
///
/// Uses [encodeRequest] and [encodeResponse] to handle further encoding.
dynamic toJsonEncodable({
required Function(Q request) encodeRequest,
required Function(R response) encodeResponse,
});
}
abstract class ResponseBuilder<Q, R> {
/// Records [response] to the previous request.
///
/// If [andBranch] is set then calls with a [Branch] to change configuration.
///
/// Can be used to build dependent responses (to mimic business logic):
/// recorder
/// .given('Hello')
/// .reply('Hi there', andBranch: (branch) {
/// branch
/// .reply('I already said hi...')
/// .always();
/// })
/// .record();
///
/// Output after branching:
/// var recording = recorder.toRecording();
/// recorder.reply('Hello'); // Hi there!
/// recorder.reply('Hello'); // I already said hi...
/// recorder.reply('Hello'); // I already said hi...
ConclusionBuilder<Q, R, Recorder<Q, R>> reply(
R response, {
void Function(Branch<Q, R> branch)? andBranch,
});
}
abstract class Branch<Q, R> implements Recorder<Q, R> {
/// Removes all responses recorded for [request].
///
/// If no response is recorded, throws [StateError].
Branch<Q, R> remove(Q request);
/// Replaces all requests recorder for [request] with [response].
///
/// If no response is recorded, throws [StateError].
ConclusionBuilder<Q, R, Branch<Q, R>> replace(Q request, R response);
}
abstract class ConclusionBuilder<Q, R, T extends Recorder<Q, R>> {
/// Records the `request->response` to _always_ return (indefinitely).
///
/// Returns back the original [Reorder].
T always();
/// Records the `request->response` queued to return once.
///
/// Returns back the original [Recorder].
T once();
/// Returns the `request->response` queued to return [times].
///
/// Returns back the original [Recorder].
T times(int times);
}
| 0 |
mirrored_repositories/DRAW/third_party/reply/lib | mirrored_repositories/DRAW/third_party/reply/lib/src/response_builder.dart | part of reply;
class _DefaultResponseBuilder<Q, R> implements ResponseBuilder<Q, R> {
final Recorder<Q, R> _recorder;
final Q _request;
_DefaultResponseBuilder(this._recorder, this._request);
@override
ConclusionBuilder<Q, R, Recorder<Q, R>> reply(
R response, {
void Function(Branch<Q, R> branch)? andBranch,
}) {
if (andBranch != null) {
throw UnimplementedError();
}
if (response == null) {
throw ArgumentError.notNull('response');
}
return _DefaultConclusionBuilder(
_recorder,
_request,
response,
);
}
}
| 0 |
mirrored_repositories/DRAW/third_party/reply/lib | mirrored_repositories/DRAW/third_party/reply/lib/src/recorder.dart | part of reply;
class _DefaultRecorder<Q, R> implements Recorder<Q, R> {
final Equality<Q> _requestEquality;
final List<Record<Q, R>> _records = <Record<Q, R>>[];
_DefaultRecorder({Equality<Q>? requestEquality})
: _requestEquality = requestEquality ?? IdentityEquality();
@override
void addRecord(Record<Q, R> record) {
_records.add(record);
}
@override
ResponseBuilder<Q, R> given(Q request) {
if (request == null) {
throw ArgumentError.notNull('request');
}
return _DefaultResponseBuilder(this, request);
}
@override
Recording<Q, R> toRecording() {
return Recording(_records, requestEquality: _requestEquality);
}
}
| 0 |
mirrored_repositories/DRAW/third_party/reply/lib | mirrored_repositories/DRAW/third_party/reply/lib/src/conclusion_builder.dart | part of reply;
class _DefaultConclusionBuilder<Q, R, T extends Recorder<Q, R>>
implements ConclusionBuilder<Q, R, T> {
final T _recorder;
final Q _request;
final R _response;
_DefaultConclusionBuilder(
this._recorder,
this._request,
this._response,
);
@override
T always() {
return _recorder
..addRecord(_DefaultRecord(_request, _response, always: true));
}
@override
T once() {
return _recorder..addRecord(_DefaultRecord(_request, _response));
}
@override
T times(int times) {
for (var i = 0; i < times; i++) {
_recorder.addRecord(_DefaultRecord(_request, _response));
}
return _recorder;
}
}
class _DefaultRecord<Q, R> implements Record<Q, R> {
@override
final bool always;
@override
final Q request;
@override
final R response;
const _DefaultRecord(this.request, this.response, {this.always = false});
}
| 0 |
mirrored_repositories/DRAW/third_party/reply/lib | mirrored_repositories/DRAW/third_party/reply/lib/src/recording.dart | part of reply;
class _DefaultRecording<Q, R> implements Recording<Q, R> {
final List<Record<Q, R>> _records;
final Equality<Q> _requestEquality;
_DefaultRecording(
Iterable<Record<Q, R>> records, {
Equality<Q>? requestEquality,
}) : _records = records.toList(),
_requestEquality = requestEquality ?? IdentityEquality();
@override
bool hasRecord(Q request) {
return _records.any((r) => _requestEquality.equals(request, r.request));
}
@override
R reply(Q request) {
for (var i = 0; i < _records.length; i++) {
if (_requestEquality.equals(_records[i].request, request)) {
return _replyAt(i);
}
}
throw StateError('No record found for $request.');
}
R _replyAt(int index) {
final record = _records[index];
if (!record.always) {
_records.removeAt(index);
}
return record.response;
}
@override
dynamic toJsonEncodable({
required Function(Q request) encodeRequest,
required Function(R response) encodeResponse,
}) =>
_records.map((record) {
return {
'always': record.always,
'request': encodeRequest(record.request),
'response': encodeResponse(record.response),
};
}).toList();
}
| 0 |
mirrored_repositories/DRAW/third_party/reply | mirrored_repositories/DRAW/third_party/reply/test/reply_test.dart | import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:reply/reply.dart';
import 'package:test/test.dart';
void main() {
group('Simple request/response', () {
late Recorder<String, String> recorder;
const notInfiniteButALot = 100;
setUp(() => recorder = Recorder<String, String>());
test('should support responding once', () {
recorder.given('Hello').reply('Hi there!').once();
final recording = recorder.toRecording();
expect(recording.hasRecord('Hello'), isTrue);
expect(recording.reply('Hello'), 'Hi there!');
expect(recording.hasRecord('Hello'), isFalse);
expect(() => recording.reply('Hello'), throwsStateError);
});
test('should support emitting a response n times', () {
recorder.given('Hello').reply('Hi there!').times(2);
final recording = recorder.toRecording();
expect(recording.reply('Hello'), 'Hi there!');
expect(recording.reply('Hello'), 'Hi there!');
expect(() => recording.reply('Hello'), throwsStateError);
});
test('should support emitting a response ∞ times', () {
recorder.given('Hello').reply('Hi there!').always();
final recording = recorder.toRecording();
for (var i = 0; i < notInfiniteButALot; i++) {
expect(recording.reply('Hello'), 'Hi there!');
}
expect(recording.hasRecord('Hello'), isTrue);
});
test('should encode as a valid JSON', () {
recorder
.given('Hello')
.reply('Hi there!')
.times(2)
.given('Thanks')
.reply('You are welcome!')
.always();
final json = recorder.toRecording().toJsonEncodable(
encodeRequest: (q) => q,
encodeResponse: (r) => r,
);
expect(json, [
{
'always': false,
'request': 'Hello',
'response': 'Hi there!',
},
{
'always': false,
'request': 'Hello',
'response': 'Hi there!',
},
{
'always': true,
'request': 'Thanks',
'response': 'You are welcome!',
},
]);
expect(jsonDecode(jsonEncode(json)), json);
final copy = Recording<String?, String?>.fromJson(
json,
toRequest: (q) => q,
toResponse: (r) => r,
);
expect(copy.hasRecord('Hello'), isTrue);
expect(copy.hasRecord('Thanks'), isTrue);
});
});
group('Custom equality', () {
late Recorder<_CustomRequest, String> recorder;
setUp(() {
recorder = Recorder<_CustomRequest, String>(
requestEquality: const _CustomRequestEquality(),
);
});
test('should be used to determine request matches', () {
recorder.given(_CustomRequest(123, 'A')).reply('Hello').once();
final recording = recorder.toRecording();
expect(
recording.hasRecord(_CustomRequest(123, 'B')),
isTrue,
);
});
});
}
class _CustomRequest {
final int idNumber;
final String name;
_CustomRequest(this.idNumber, this.name);
}
class _CustomRequestEquality implements Equality<_CustomRequest> {
const _CustomRequestEquality();
@override
bool equals(_CustomRequest e1, _CustomRequest e2) {
return e1.idNumber == e2.idNumber;
}
@override
int hash(_CustomRequest e) => e.idNumber;
@override
bool isValidKey(Object? o) => o is _CustomRequest;
}
| 0 |
mirrored_repositories/DRAW | mirrored_repositories/DRAW/example/example.dart | // Copyright (c) 2018, the Dart Reddit API Wrapper project authors.
// Please see the AUTHORS file for details. All rights reserved.
// Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
import 'dart:async';
import 'package:draw/draw.dart';
String? kClientId;
String? kSecret;
String? kAgentName;
Future<void> main() async {
// Create the `Reddit` instance and authenticate
final reddit = await Reddit.createScriptInstance(
clientId: kClientId,
clientSecret: kSecret,
userAgent: kAgentName,
username: 'DRAWApiOfficial',
password: 'hunter12', // Fake
);
// Retrieve information for the currently authenticated user
final currentUser = (await reddit.user.me()) as Redditor;
// Outputs: My name is DRAWApiOfficial
print('My name is ${currentUser.displayName}');
}
| 0 |
mirrored_repositories/uniMindeloApp | mirrored_repositories/uniMindeloApp/lib/main.dart | // @dart=2.9
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:get_storage/get_storage.dart';
import 'package:google_fonts/google_fonts.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:splashscreen/splashscreen.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/utils/services/router.dart';
import 'package:uni_mindelo/utils/services/storage.service.dart';
import 'package:uni_mindelo/views/home/home.dart';
import 'dart:ui' as ui;
//Views
import './views/auth/login/login.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
var delegate = await LocalizationDelegate.create(
fallbackLocale: 'pt', supportedLocales: ['pt']);
await GetStorage.init();
//Remove Death Red Screen DEBUG
RenderErrorBox.backgroundColor = Colors.transparent;
RenderErrorBox.textStyle = ui.TextStyle(color: Colors.transparent);
ErrorWidget.builder = (FlutterErrorDetails details) {
return Container();
};
runApp(LocalizedApp(delegate, Main()));
}
class Main extends StatelessWidget {
@override
Widget build(BuildContext context) {
final Future<FirebaseApp> _fbApp = Firebase.initializeApp();
var localizationDelegate = LocalizedApp.of(context).delegate;
return LocalizationProvider(
state: LocalizationProvider.of(context).state,
child: MaterialApp(
onGenerateRoute: AppRouter.generateRoute,
initialRoute: loginRoute,
localizationsDelegates: [localizationDelegate],
debugShowCheckedModeBanner: true,
theme: ThemeData(
primaryColor: PrimaryColor,
scaffoldBackgroundColor: PrimaryWhiteAssentColor,
visualDensity: VisualDensity.adaptivePlatformDensity,
textTheme: GoogleFonts.latoTextTheme(
Theme.of(context).textTheme,
)),
home: FutureBuilder(
future: _fbApp,
builder: (context, snapshot) {
if (snapshot.hasError) {
print('erro ${snapshot.error.toString()}');
return Text("erro");
} else if (snapshot.hasData) {
if (getData(user_uid) != null) {
return Splash(homeRoute);
} else {
return Splash(loginRoute);
}
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}),
builder: EasyLoading.init(),
),
);
}
}
class Splash extends StatelessWidget {
Splash(this.route);
final String route;
@override
Widget build(BuildContext context) {
return new SplashScreen(
seconds: 3,
navigateAfterSeconds: route == homeRoute ? Home() : Login(),
backgroundColor: Colors.white,
imageBackground: AssetImage('assets/images/home.jpeg'),
photoSize: 20,
loaderColor: PrimaryBlack);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib | mirrored_repositories/uniMindeloApp/lib/apis/fireBaseCalls.dart | import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:uni_mindelo/utils/constants/errors.dart';
import 'package:uni_mindelo/utils/services/dialogService.dart';
import 'package:uni_mindelo/utils/services/loaderService.dart';
import 'package:uni_mindelo/utils/services/router.dart';
import 'package:uni_mindelo/utils/services/storage.service.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
final _auth = FirebaseAuth.instance;
final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
final userID = getData(user_uid);
final classID = getData(classId);
login(email, password, BuildContext context) async {
try {
showLoader();
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((value) => {
saveData(user_uid, value.user!.uid),
dismissLoader(),
Navigator.pushNamed(context, homeRoute)
});
} on FirebaseAuthException catch (error) {
dismissLoader();
authErrorHandler(error.code, context);
}
}
forgotPassword(email, BuildContext context) async {
try {
showLoader();
await _auth.sendPasswordResetEmail(email: email).then((_value) => {
showDialog(
context: context,
builder: (BuildContext context) {
return DialogService(
subTitle: 'FORGOT_PASSWORD.EMAIL_SEND',
title: 'DIALOG.HEADER.SUCCESS',
dismissOnPopLogin: true,
isCreditCard: false);
}),
dismissLoader()
});
} on FirebaseAuthException catch (error) {
dismissLoader();
authErrorHandler(error.code, context);
}
}
getUserData() {
return _fireStore.collection('Users').doc(userID).get();
}
getFeedData() {
return _fireStore.collection('Feed').snapshots();
}
getUserClasses() {
return _fireStore
.collection('ClassesSchedule')
.where('classId', isEqualTo: classID)
.snapshots();
}
getUserBribes() {
return _fireStore
.collection('UserBribes')
.where('userId', isEqualTo: userID)
.snapshots();
}
cineMindeloMovies() {
return _fireStore.collection('CineMindeloMovies').snapshots();
}
authErrorHandler(errorCode, context) {
switch (errorCode) {
case userDontExists:
showDialog(
context: context,
builder: (BuildContext context) {
return DialogService(
subTitle: 'ERRORS.USER_DONT_EXISTS',
title: 'DIALOG.HEADER.ERROR',
dismissOnPopLogin: false,
isCreditCard: false);
});
break;
case wrongPassword:
showDialog(
context: context,
builder: (BuildContext context) {
return DialogService(
subTitle: 'ERRORS.WRONG_PASSWORD',
title: 'DIALOG.HEADER.ERROR',
dismissOnPopLogin: false,
isCreditCard: false);
});
break;
case tooManyRequests:
showDialog(
context: context,
builder: (BuildContext context) {
return DialogService(
subTitle: 'ERRORS.TOO_MANY_REQUESTS',
title: 'DIALOG.HEADER.WARNING',
dismissOnPopLogin: false,
isCreditCard: false);
});
break;
case invalidEmail:
showDialog(
context: context,
builder: (BuildContext context) {
return DialogService(
subTitle: 'ERRORS.INVALID_EMAIL',
title: 'DIALOG.HEADER.ERROR',
dismissOnPopLogin: false,
isCreditCard: false);
});
break;
default:
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views | mirrored_repositories/uniMindeloApp/lib/views/classes/classes.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:flutter_week_view/flutter_week_view.dart';
import 'package:uni_mindelo/apis/fireBaseCalls.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/widgets/appBar.dart';
// ignore: must_be_immutable
class Classes extends StatefulWidget {
@override
_ClassesState createState() => _ClassesState();
}
class _ClassesState extends State<Classes> {
Widget build(BuildContext context) {
final Stream<QuerySnapshot> _usersClasses = getUserClasses();
DateTime now = DateTime.now();
DateTime date = DateTime(now.year, now.month, now.day);
List<FlutterWeekViewEvent> classes = [];
return StreamBuilder<QuerySnapshot>(
stream: _usersClasses,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
var getClasses = snapshot.data!.docs.map((DocumentSnapshot document) {
return document.data() as Map<String, dynamic>;
}).toList();
getClasses.forEach((el) => {
classes.add(
FlutterWeekViewEvent(
title: el["title"],
description: el["description"],
start: date.add(Duration(hours: 9)),
end: date.add(Duration(hours: 13)),
),
)
});
return new Scaffold(
appBar: CustomAppbar(
title: translate("APP_BAR.TITLE.CLASSES"),
canBack: true,
),
body: Stack(children: <Widget>[
Container(
child: WeekView(
userZoomable: true,
dates: [
date.subtract(Duration(days: 1)),
date,
date.add(Duration(days: 1))
],
events: classes,
style: WeekViewStyle(
dayViewSeparatorWidth: 5,
dayViewSeparatorColor: currentTimeCircleColor)))
]),
);
},
);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views | mirrored_repositories/uniMindeloApp/lib/views/grades/grades.dart | import 'package:flutter/material.dart';
import 'package:expansion_tile_card/expansion_tile_card.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:flutter_email_sender/flutter_email_sender.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/utils/services/launchUrlService.dart';
import 'package:uni_mindelo/widgets/appBar.dart';
// ignore: must_be_immutable
class Grades extends StatefulWidget {
var userGrades;
Grades({this.userGrades});
@override
_GradesState createState() => _GradesState();
}
class _GradesState extends State<Grades> {
Widget build(BuildContext context) {
List getUserGrades = getGrades(widget.userGrades);
return Scaffold(
appBar: CustomAppbar(
title: translate("APP_BAR.TITLE.GRADES"),
canBack: true,
),
body: Stack(
children: <Widget>[
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: getUserGrades.length,
itemBuilder: (context, int index) {
final GlobalKey<ExpansionTileCardState> cards = new GlobalKey();
final userGrade = List.from(getUserGrades[index]);
final gradeColor = double.parse(userGrade[index]["grade"]) <= 9
? gradesNOK
: gradesOK;
final userAprovedNotAprovedf =
double.parse(userGrade[index]["grade"]) <= 9
? translate('GRADES.GRADE_NOK')
: translate('GRADES.GRADE_OK') +
userGrade[index]["grade"] +
translate('GRADES.VALUE');
return Container(
child: ExpansionTileCard(
key: cards,
leading: CircleAvatar(
backgroundColor: gradeColor,
foregroundColor: PrimaryWhiteAssentColor,
child: Text(userGrade[index]["grade"])),
title: Text(userGrade[index]["title"]),
children: <Widget>[
Divider(
thickness: 1.0,
height: 1.0,
),
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 8.0,
),
child: Text(
translate('GRADES.PROFESSOR_GRADE') +
'\n' +
userGrade[index]["teacher"] +
'\n' +
userAprovedNotAprovedf,
style: Theme.of(context)
.textTheme
.bodyText2!
.copyWith(fontSize: 16),
),
),
),
ButtonBar(
alignment: MainAxisAlignment.spaceAround,
buttonHeight: 52.0,
buttonMinWidth: 90.0,
children: <Widget>[
TextButton(
onPressed: () {
send(userGrade[index]["teacherEmail"],
userGrade[index]["grade"]);
},
child: Column(
children: <Widget>[
Icon(Icons.email),
Padding(
padding:
const EdgeInsets.symmetric(vertical: 2.0),
),
Text(translate('GRADES.BT_MAIL')),
],
),
),
TextButton(
onPressed: () {
launchURL(
'http://www.pdf995.com/samples/pdf.pdf');
},
child: Column(
children: <Widget>[
Icon(Icons.file_download),
Padding(
padding:
const EdgeInsets.symmetric(vertical: 2.0),
),
Text(translate('GRADES.BT_DOWNLOAD')),
],
),
),
],
),
],
),
);
}),
],
),
);
}
}
List getGrades(userGrades) {
return new List.filled(userGrades.length, userGrades, growable: true);
}
Future<void> send(recipientEmail, grade) async {
final Email email = Email(
body: translate('GRADES.EMAIL_BODY') + grade + translate('GRADES.VALUES'),
subject: translate('GRADES.EMAIL_SUBJECT'),
recipients: [recipientEmail],
isHTML: true,
);
try {
await FlutterEmailSender.send(email);
print("Email Enviado");
} catch (error) {
print(error);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views/auth | mirrored_repositories/uniMindeloApp/lib/views/auth/forgotPassword/forgotPassword.dart | import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:uni_mindelo/Widgets/background.dart';
import 'package:uni_mindelo/apis/fireBaseCalls.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/widgets/appBar.dart';
class ForgotPassword extends StatefulWidget {
@override
_ForgotPasswordState createState() => _ForgotPasswordState();
}
class _ForgotPasswordState extends State<ForgotPassword> {
static String email = "";
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: CustomAppbar(
title: translate("APP_BAR.TITLE.FORGOT_PASSWORD"),
canBack: true,
),
body: Background(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.symmetric(horizontal: 40),
child: Image.asset("assets/images/logo.png",
width: size.width * 0.35),
),
SizedBox(height: size.height * 0.03),
Container(
alignment: Alignment.center,
margin: EdgeInsets.symmetric(horizontal: 40),
child: TextField(
keyboardType: TextInputType.emailAddress,
onChanged: (value) {
setState(() {
email = value;
});
},
decoration: InputDecoration(
labelText: translate('FORGOT_PASSWORD.USERNAME'),
),
),
),
SizedBox(height: size.height * 0.03),
SizedBox(height: size.height * 0.05),
Container(
alignment: Alignment.centerRight,
margin: EdgeInsets.symmetric(horizontal: 40, vertical: 10),
// ignore: deprecated_member_use
child: RaisedButton(
onPressed: () {
setState(() {
forgotPassword(email, context);
});
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
textColor: PrimaryBlackAssentColor,
padding: const EdgeInsets.all(0),
child: Container(
alignment: Alignment.center,
height: 50.0,
width: size.width * 0.5,
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: PrimaryColor,
),
padding: const EdgeInsets.all(0),
child: Text(
translate('FORGOT_PASSWORD.BT_TITLE'),
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views/auth | mirrored_repositories/uniMindeloApp/lib/views/auth/login/login.dart | import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:uni_mindelo/Widgets/background.dart';
import 'package:uni_mindelo/apis/fireBaseCalls.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/utils/services/router.dart';
class Login extends StatefulWidget {
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
static String email = "";
static String password = "";
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
resizeToAvoidBottomInset: false,
body: Background(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.symmetric(horizontal: 40),
child: Image.asset("assets/images/logo.png",
width: size.width * 0.35),
),
SizedBox(height: size.height * 0.03),
Container(
alignment: Alignment.center,
margin: EdgeInsets.symmetric(horizontal: 40),
child: TextField(
keyboardType: TextInputType.emailAddress,
onChanged: (value) {
setState(() {
email = value;
});
},
decoration: InputDecoration(
labelText: translate('LOGIN.USERNAME'),
),
),
),
SizedBox(height: size.height * 0.03),
Container(
alignment: Alignment.center,
margin: EdgeInsets.symmetric(horizontal: 40),
child: TextField(
onChanged: (value) {
setState(() {
password = value;
});
},
decoration:
InputDecoration(labelText: translate('LOGIN.PASSWORD')),
obscureText: true,
),
),
Container(
alignment: Alignment.centerRight,
margin: EdgeInsets.symmetric(horizontal: 40, vertical: 20),
child: new GestureDetector(
onTap: () {
Navigator.pushNamed(context, forgorPassword);
},
child: Text(
translate('LOGIN.FORGOT_PASSWORD'),
style: TextStyle(
fontSize: 12,
color: PrimaryBlackAssentColor,
decoration: TextDecoration.underline),
),
),
),
SizedBox(height: size.height * 0.05),
Container(
alignment: Alignment.centerRight,
margin: EdgeInsets.symmetric(horizontal: 40, vertical: 10),
// ignore: deprecated_member_use
child: RaisedButton(
onPressed: () {
setState(() {
login(email, password, context);
});
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
textColor: PrimaryBlackAssentColor,
padding: const EdgeInsets.all(0),
child: Container(
alignment: Alignment.center,
height: 50.0,
width: size.width * 0.5,
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: PrimaryColor,
),
padding: const EdgeInsets.all(0),
child: Text(
translate('LOGIN.BT_TITLE'),
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views | mirrored_repositories/uniMindeloApp/lib/views/home/home.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:sliding_up_panel/sliding_up_panel.dart';
import 'package:uni_mindelo/apis/fireBaseCalls.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/utils/services/router.dart';
import 'package:uni_mindelo/utils/services/storage.service.dart';
import 'package:uni_mindelo/widgets/appBar.dart';
import 'package:uni_mindelo/widgets/drawer.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool _isOpen = false;
PanelController _panelController = PanelController();
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppbar(
title: translate("APP_BAR.TITLE.HOME"),
canBack: false,
),
body: FutureBuilder<DocumentSnapshot>(
future: getUserData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
saveData(classId, snapshot.data?.get('classId'));
return Stack(
fit: StackFit.expand,
children: <Widget>[
/* Text(userData!['data']['userName']), */
FractionallySizedBox(
alignment: Alignment.topCenter,
heightFactor: 0.6,
widthFactor: 4,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/home.jpeg'),
fit: BoxFit.cover),
),
),
),
FractionallySizedBox(
alignment: Alignment.bottomCenter,
heightFactor: 0.3,
child: Container(
color: Colors.white,
),
),
SlidingUpPanel(
controller: _panelController,
borderRadius: BorderRadius.only(
topRight: Radius.circular(32),
topLeft: Radius.circular(32),
),
minHeight: MediaQuery.of(context).size.height * 0.35,
maxHeight: MediaQuery.of(context).size.height * 0.85,
body: GestureDetector(
onTap: () => _panelController.close(),
child: Container(
color: Colors.transparent,
),
),
panelBuilder: (ScrollController controller) =>
_panelBody(controller, snapshot.data?.data()),
onPanelSlide: (value) {
if (value >= 0.2) {
if (!_isOpen) {
setState(() {
_isOpen = true;
});
}
}
},
onPanelClosed: () {
setState(() {
_isOpen = false;
_panelController.close();
});
},
),
],
); //Center(child: Text(snapshot.data!['userName']));
} else {
return Center(
child: CircularProgressIndicator(),
);
}
}),
drawer: CustomDrawer(),
);
}
/// Panel Body
SingleChildScrollView _panelBody(ScrollController controller, user) {
double hPadding = 30;
return SingleChildScrollView(
controller: controller,
physics: ClampingScrollPhysics(),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: hPadding),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 60,
),
child: Column(
children: [
_titleSection(user),
_actionSection(hPadding: hPadding, user: user),
],
),
),
],
),
),
],
),
);
}
/// Action Section
Row _actionSection({required double hPadding, user}) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Visibility(
visible: !_isOpen,
child: Expanded(
child: Container(
margin: EdgeInsets.only(top: 20),
// ignore: deprecated_member_use
child: OutlineButton(
onPressed: () => _panelController.open(),
borderSide: BorderSide(color: Colors.blue),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
child: Text(
translate('HOME.PROFILE'),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
),
),
),
),
),
),
Visibility(
visible: !_isOpen,
child: SizedBox(
width: 16,
),
),
Expanded(
child: Container(
alignment: Alignment.center,
child: Column(
children: <Widget>[
Container(
child: Visibility(
visible: !_isOpen,
child: SizedBox(
width: !_isOpen
? (MediaQuery.of(context).size.width -
(2 * hPadding)) /
1.6
: double.infinity,
child: Container(
margin: EdgeInsets.only(top: 20),
// ignore: deprecated_member_use
child: FlatButton(
onPressed: () => Navigator.pushNamed(
context, gradesRoute,
arguments: user!['grades'] ?? ''),
color: PrimaryColor,
textColor: PrimaryWhiteAssentColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
child: Text(
translate('HOME.GRADES'),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
),
),
),
),
),
),
),
Visibility(
visible: _isOpen,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 20,
),
CircleAvatar(
radius: 50,
backgroundImage:
AssetImage('assets/images/avatar.png'),
),
SizedBox(
height: 10,
),
Card(
color: PrimaryColor,
child: ListTile(
leading: Icon(Icons.phone,
color: PrimaryWhiteAssentColor),
title: Text(user!["phoneNumber"] ?? '',
style: TextStyle(
color: PrimaryWhiteAssentColor,
)),
),
),
SizedBox(
height: 10,
),
Card(
color: PrimaryColor,
child: ListTile(
leading: Icon(Icons.email,
color: PrimaryWhiteAssentColor),
title: Text(user!["email"] ?? '',
style: TextStyle(
color: PrimaryWhiteAssentColor,
)),
),
),
SizedBox(
height: 10,
),
Card(
color: PrimaryColor,
child: ListTile(
leading: Icon(Icons.cake,
color: PrimaryWhiteAssentColor),
title: Text(
((user!["birthDay"] ?? '' as Timestamp)
.toDate()
.toString()
.split(" ")
.first),
style: TextStyle(
color: PrimaryWhiteAssentColor,
)),
),
),
SizedBox(
height: 10,
),
Card(
color: PrimaryColor,
child: ListTile(
leading: Icon(Icons.fingerprint,
color: PrimaryWhiteAssentColor),
title: Text('ID ' + user!["id_student"],
style: TextStyle(
color: PrimaryWhiteAssentColor,
)),
),
),
SizedBox(
height: 10,
),
Card(
color: isPaid,
child: ListTile(
leading: Icon(
Icons.credit_card,
),
title: Text(
user!["isPaid"].toString() == 'true'
? 'Propina Paga'
: 'Propina por Pagar',
style: TextStyle(
color: PrimaryBlackAssentColor,
)),
),
),
SizedBox(
height: 10,
),
Card(
semanticContainer: true,
clipBehavior: Clip.antiAliasWithSaveLayer,
child: Image.asset(
'assets/images/qr_placeholder.png',
fit: BoxFit.cover,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
elevation: 5,
margin: EdgeInsets.all(5),
),
],
),
)),
],
),
),
),
],
);
}
/// Title Section
Column _titleSection(user) {
return Column(
children: <Widget>[
Visibility(
// ignore: unnecessary_null_comparison
visible: user != null,
child: Column(
children: [
Text(
user!['userName'] + ' ' + user!['userSurname'],
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 30,
),
),
SizedBox(
height: 8,
),
Text(
user!['course'],
style: TextStyle(
fontSize: 16,
),
),
SizedBox(
height: 8,
),
Text(
user!['semester'] + ' ' + translate('HOME.SEMESTER'),
style: TextStyle(
fontSize: 16,
),
),
],
),
),
],
);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views | mirrored_repositories/uniMindeloApp/lib/views/feed/feed.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:octo_image/octo_image.dart';
import 'package:uni_mindelo/apis/fireBaseCalls.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/utils/services/launchUrlService.dart';
import 'package:uni_mindelo/widgets/appBar.dart';
import 'package:uni_mindelo/widgets/drawer.dart';
import 'package:share/share.dart';
class Feed extends StatefulWidget {
@override
_FeedState createState() => _FeedState();
}
class _FeedState extends State<Feed> {
Map<String, dynamic> feeds = {};
Widget build(BuildContext context) {
final Stream<QuerySnapshot> _usersStream = getFeedData();
return StreamBuilder<QuerySnapshot>(
stream: _usersStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return new Scaffold(
appBar: CustomAppbar(
title: translate("APP_BAR.TITLE.FEED"),
canBack: false,
),
drawer: CustomDrawer(),
//bottomNavigationBar: CustomBottomNavigationBar(),
body: Stack(children: <Widget>[
Container(
child: Card(
elevation: 10,
shadowColor: bottomNavigationBarTheme,
clipBehavior: Clip.antiAlias,
child: ListView(
children:
snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> feed =
document.data() as Map<String, dynamic>;
return Column(
children: [
new ListTile(
leading: CircleAvatar(
radius: 30,
backgroundColor: PrimaryWhiteAssentColor,
child: Image.asset('assets/images/logo.png'),
),
title: Text(feed["title"]),
),
OctoImage(
image: NetworkImage(feed["img"]),
progressIndicatorBuilder: (context, progress) {
double? value;
var expectedBytes = progress?.expectedTotalBytes;
if (progress != null && expectedBytes != null) {
value = progress.cumulativeBytesLoaded /
expectedBytes;
}
return CircularProgressIndicator(value: value);
},
errorBuilder: (context, error, stacktrace) =>
Icon(Icons.error),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
feed["subTitle"],
style:
TextStyle(color: Colors.black.withOpacity(0.6)),
),
),
ButtonBar(
alignment: MainAxisAlignment.end,
buttonHeight: 20.0,
buttonMinWidth: 20.0,
children: <Widget>[
TextButton(
onPressed: () {
launchURL(feed["url"]);
},
child: Column(
children: <Widget>[
Icon(
Icons.facebook,
size: 30,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 1.0),
),
],
),
),
TextButton(
onPressed: () {
Share.share(
feed["url"],
);
},
child: Column(
children: <Widget>[
Icon(
Icons.share,
size: 30,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 1.0),
),
],
),
),
],
),
new Divider(
height: 5,
color: PrimaryGreyColor,
thickness: 5.0,
),
],
);
}).toList(),
),
),
),
]),
);
},
);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views | mirrored_repositories/uniMindeloApp/lib/views/cineMindelo/cineMindelo.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:octo_image/octo_image.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:ticketview/ticketview.dart';
import 'package:uni_mindelo/apis/fireBaseCalls.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/utils/constants/paymentTitle.dart';
import 'package:uni_mindelo/utils/services/launchUrlService.dart';
import 'package:uni_mindelo/utils/services/router.dart';
import 'package:uni_mindelo/widgets/appBar.dart';
import 'package:uni_mindelo/widgets/drawer.dart';
// ignore: unused_import
import 'package:transparent_image/transparent_image.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:worm_indicator/shape.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:worm_indicator/worm_indicator.dart';
class CineMindelo extends StatefulWidget {
@override
_CineMindeloState createState() => _CineMindeloState();
}
class _CineMindeloState extends State<CineMindelo> {
Widget build(BuildContext context) {
PageController _controller = PageController(
initialPage: 0,
);
final Stream<QuerySnapshot> _cineMindelo = cineMindeloMovies();
return StreamBuilder<QuerySnapshot>(
stream: _cineMindelo,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return new Scaffold(
appBar: CustomAppbar(
title: translate("APP_BAR.TITLE.CINE_MINDELO"),
canBack: false,
),
drawer: CustomDrawer(),
bottomNavigationBar: SizedBox(
height: 18,
child: WormIndicator(
length: 2,
controller: _controller,
shape: Shape(
size: 16,
spacing: 8,
shape: DotShape.Circle // Similar for Square
),
)),
body: PageView(
controller: _controller,
children: <Widget>[
Container(
height: 200,
child: Card(
margin: EdgeInsets.all(10),
semanticContainer: true,
clipBehavior: Clip.antiAliasWithSaveLayer,
elevation: 5,
shadowColor: bottomNavigationBarTheme,
child: ListView(
children:
snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> movies =
document.data() as Map<String, dynamic>;
return Column(
children: [
ListTile(
leading: CircleAvatar(
radius: 20,
backgroundImage:
AssetImage('assets/images/cineMindelo.jpg'),
),
title: Text(
'${movies["title"]} e ${movies["subTitle"]}'),
subtitle: RichText(
text: TextSpan(
style: Theme.of(context).textTheme.bodyText1,
children: [
TextSpan(
text:
'${translate('TICKETS.PRICE')} ${movies["price"]}',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
)),
WidgetSpan(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 0.0),
child: Icon(
Icons.attach_money,
size: 18,
),
),
),
],
),
),
),
OctoImage(
image: NetworkImage(movies["img"]),
progressIndicatorBuilder: (context, progress) {
double? value;
var expectedBytes = progress?.expectedTotalBytes;
if (progress != null && expectedBytes != null) {
value = progress.cumulativeBytesLoaded /
expectedBytes;
}
return CircularProgressIndicator(value: value);
},
errorBuilder: (context, error, stacktrace) =>
Icon(Icons.error),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
movies["description"],
style: TextStyle(
color: Colors.black.withOpacity(0.6)),
),
),
ButtonBar(
alignment: MainAxisAlignment.end,
buttonHeight: 10.0,
buttonMinWidth: 10.0,
children: <Widget>[
TextButton(
onPressed: () {
Navigator.pushNamed(context, payment,
arguments: buyTicket);
},
child: Column(
children: <Widget>[
Icon(
Icons.add_shopping_cart,
size: 30,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 1.0),
),
],
),
),
TextButton(
onPressed: () {
launchURL(
movies["ytUrl"],
);
},
child: Column(
children: <Widget>[
Icon(
Icons.smart_display,
size: 30,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 1.0),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 1.0),
),
],
),
),
],
),
new Divider(
height: 5,
color: PrimaryGreyColor,
thickness: 5.0,
),
],
);
}).toList(),
),
),
),
TicketView(
backgroundPadding:
EdgeInsets.symmetric(vertical: 0, horizontal: 20),
backgroundColor: PrimaryColor,
contentPadding:
EdgeInsets.symmetric(vertical: 24, horizontal: 0),
drawArc: true,
triangleAxis: Axis.vertical,
borderRadius: 6,
drawDivider: true,
trianglePos: .5,
child: Container(
child: Column(
children: <Widget>[
Expanded(
flex: 5,
child: Container(
padding: EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Text(
'${translate('TICKETS.MOVIE')} Jumani Next Level - 2 horas',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
)),
],
),
SizedBox(height: 14),
Text(
'${translate('TICKETS.PLACE')} Auditório Onésimo Silveira - UniMindelo',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
)),
SizedBox(height: 14),
Text('${translate('TICKETS.PRICE')} 200 \$',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
)),
SizedBox(height: 14),
Text(
'${translate('TICKETS.DATE')} 29/01/2022 - 19H00',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
)),
SizedBox(height: 14),
Text('${translate('TICKETS.PEOPLE')}: 1',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
)),
SizedBox(height: 14),
Text(translate('TICKETS.INFO'),
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
)),
],
),
),
),
Expanded(
flex: 5,
child: Container(
margin: EdgeInsets.symmetric(vertical: 30),
child:
Image.asset('assets/images/qr_placeholder.png'),
),
),
],
),
),
)
],
),
);
},
);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views | mirrored_repositories/uniMindeloApp/lib/views/payment/paymentsList.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:uni_mindelo/apis/fireBaseCalls.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/utils/constants/paymentTitle.dart';
import 'package:uni_mindelo/utils/services/launchUrlService.dart';
import 'package:uni_mindelo/utils/services/router.dart';
import 'package:uni_mindelo/widgets/appBar.dart';
import 'package:uni_mindelo/widgets/drawer.dart';
class Bribes extends StatefulWidget {
@override
_BridesState createState() => _BridesState();
}
class _BridesState extends State<Bribes> {
Widget build(BuildContext context) {
final Stream<QuerySnapshot> _userBribes = getUserBribes();
List<dynamic> bribes = [];
return StreamBuilder<QuerySnapshot>(
stream: _userBribes,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
bribes = snapshot.data!.docs.map((DocumentSnapshot document) {
return document.data() as Map<String, dynamic>;
}).toList();
return new Scaffold(
appBar: CustomAppbar(
title: translate("APP_BAR.TITLE.BRIBES"),
canBack: false,
),
drawer: CustomDrawer(),
body: Stack(children: [cardsList(context, bribes)]));
},
);
}
}
Column cardsList(context, userbribes) {
return new Column(
children: <Widget>[
for (int i = 0; i < userbribes.length; i++)
Card(
clipBehavior: Clip.antiAlias,
child: Column(
children: [
ListTile(
leading: Icon(
Icons.payment,
size: 50,
color: userbribes[i]["isPaid"] == true
? PrimaryColor
: isNotPaid,
),
title: Text(
'${translate("PAYMENT.PAYMENT_REFERENCE")} ${convertTimeStamp(userbribes[i]["duePayment"])}',
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(
'${translate("PAYMENT.AMOUNT_TO_PAY")} ${userbribes[i]["amount"]} CVE',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
userbribes[i]["isPaid"] == false
? translate("PAYMENT.PAYMENT_DUE")
: translate("PAYMENT.PAYMENT_DUE_PAID"),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
))),
ButtonBar(
alignment: MainAxisAlignment.end,
children: [
userbribes[i]["isPaid"] == false
// ignore: deprecated_member_use
? FlatButton(
textColor: PrimaryColor,
onPressed: () {
Navigator.pushNamed(context, payment,
arguments: payBribe);
},
child: Text(
translate("PAYMENT.BT_PAY"),
style: TextStyle(
fontWeight: FontWeight.bold,
color: isNotPaid,
fontSize: 15,
),
),
)
// ignore: deprecated_member_use
: FlatButton(
textColor: PrimaryColor,
onPressed: () {
launchURL('http://www.pdf995.com/samples/pdf.pdf');
},
child: Text(
translate("PAYMENT.BT_PAY_INVOICE"),
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: PrimaryColor),
),
),
],
),
],
),
),
],
);
}
convertTimeStamp(timestamp) {
final date = DateTime.parse(timestamp.toDate().toString());
return '${date.day}/${date.month}/${date.year}';
}
| 0 |
mirrored_repositories/uniMindeloApp/lib/views | mirrored_repositories/uniMindeloApp/lib/views/payment/payments.dart | import 'package:flutter/material.dart';
import 'package:flutter_credit_card/credit_card_form.dart';
import 'package:flutter_credit_card/credit_card_model.dart';
import 'package:flutter_credit_card/flutter_credit_card.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:uni_mindelo/utils/constants/colors.dart';
import 'package:uni_mindelo/utils/services/dialogService.dart';
import 'package:uni_mindelo/widgets/appBar.dart';
// ignore: must_be_immutable
class Payment extends StatefulWidget {
var title;
Payment({this.title});
@override
State<StatefulWidget> createState() {
return PaymentState();
}
}
class PaymentState extends State<Payment> {
String cardNumber = '';
String expiryDate = '';
String cardHolderName = '';
String cvvCode = '';
bool isCvvFocused = false;
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: CustomAppbar(
title: widget.title,
canBack: false,
),
resizeToAvoidBottomInset: true,
body: SafeArea(
child: Column(
children: <Widget>[
CreditCardWidget(
cardBgColor: creditCardColor,
cardNumber: cardNumber,
expiryDate: expiryDate,
cardHolderName: cardHolderName,
cvvCode: cvvCode,
showBackView: isCvvFocused,
obscureCardNumber: true,
// ignore: non_constant_identifier_names
obscureCardCvv: true,
// ignore: non_constant_identifier_names
onCreditCardWidgetChange: (CreditCardBrand) {},
),
Expanded(
child: SingleChildScrollView(
child: Column(
children: [
CreditCardForm(
formKey: formKey,
onCreditCardModelChange: onCreditCardModelChange,
obscureCvv: true,
obscureNumber: true,
cardNumberDecoration: InputDecoration(
border: OutlineInputBorder(),
labelText: translate("PAYMENT.LABEL_NUMBER"),
hintText: translate("PAYMENT.HINT_NUMBER"),
),
expiryDateDecoration: InputDecoration(
border: OutlineInputBorder(),
labelText: translate("PAYMENT.LABEL_DATE"),
hintText: translate("PAYMENT.HINT_DATE"),
),
cvvCodeDecoration: InputDecoration(
border: OutlineInputBorder(),
labelText: translate("PAYMENT.LABEL_CVV"),
hintText: translate("PAYMENT.HINT_CVV"),
),
cardHolderDecoration: InputDecoration(
border: OutlineInputBorder(),
labelText: translate("PAYMENT.LABEL_CARD_HOLDER"),
),
cardHolderName: '',
cardNumber: '',
cvvCode: '',
expiryDate: '',
themeColor: creditCardColorBtPay,
),
SizedBox(
height: 20,
),
// ignore: deprecated_member_use
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
child: Container(
margin: const EdgeInsets.all(15),
width: 100,
child: Text(
translate("PAYMENT.BT_PAY"),
softWrap: true,
textAlign: TextAlign.center,
style: TextStyle(
color: PrimaryWhiteAssentColor,
fontSize: 18,
),
),
),
color: creditCardColorBtPay,
onPressed: () {
if (formKey.currentState!.validate()) {
_showDialog(translate("PAYMENT.VALID_PAYMENT_TITLE"),
translate("PAYMENT.VALID_PAYMENT_SUBTITLE"));
/* DO SOMETHING ON THE SERVER */
} else {}
},
)
],
),
),
),
],
),
),
);
}
_showDialog(String title, String subTitle) {
showDialog(
context: context,
builder: (BuildContext context) {
return DialogService(
subTitle: subTitle,
title: title,
dismissOnPopLogin: false,
isCreditCard: true);
});
}
void onCreditCardModelChange(CreditCardModel creditCardModel) {
setState(() {
cardNumber = creditCardModel.cardNumber;
expiryDate = creditCardModel.expiryDate;
cardHolderName = creditCardModel.cardHolderName;
cvvCode = creditCardModel.cvvCode;
isCvvFocused = creditCardModel.isCvvFocused;
});
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib | mirrored_repositories/uniMindeloApp/lib/widgets/background.dart | import 'package:flutter/material.dart';
// BACKGROUND
class Background extends StatelessWidget {
final Widget child;
const Background({
required this.child,
});
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
width: double.infinity,
height: size.height,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Positioned(
top: 0,
right: 0,
child: Image.asset("assets/images/top1.png", width: size.width),
),
Positioned(
top: 0,
right: 0,
child: Image.asset("assets/images/top2.png", width: size.width),
),
Positioned(
bottom: 0,
right: 0,
child: Image.asset("assets/images/bottom1.png", width: size.width),
),
Positioned(
bottom: 0,
right: 0,
child: Image.asset("assets/images/bottom2.png", width: size.width),
),
child
],
),
);
}
}
| 0 |
mirrored_repositories/uniMindeloApp/lib | mirrored_repositories/uniMindeloApp/lib/widgets/drawer.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:uni_mindelo/utils/services/launchUrlService.dart';
import 'package:uni_mindelo/utils/services/router.dart';
import 'package:uni_mindelo/utils/services/storage.service.dart';
class CustomDrawer extends StatefulWidget {
const CustomDrawer({Key? key}) : super(key: key);
@override
_CustomDrawerState createState() => _CustomDrawerState();
}
class _CustomDrawerState extends State<CustomDrawer> {
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
header(),
item(
icon: Icons.contacts,
text: translate('DRAWER.TITLE.HOME'),
onTap: () => pushToView(homeRoute)),
item(
icon: Icons.feed,
text: translate('DRAWER.TITLE.FEED'),
onTap: () => pushToView(feedRoute)),
item(
icon: Icons.event,
text: translate('DRAWER.TITLE.CLASSES'),
onTap: () => pushToView(classes)),
item(
icon: Icons.payment,
text: translate('DRAWER.TITLE.BRIBES'),
onTap: () => pushToView(bribes)),
item(
icon: Icons.movie_filter,
text: translate('DRAWER.TITLE.MOVIES'),
onTap: () => pushToView(cineMindelo)),
item(
icon: Icons.school,
text: translate('DRAWER.TITLE.MOODLE'),
onTap: () => {
launchURL('https://moodle.um.edu.cv/'),
}),
item(
icon: Icons.facebook,
text: translate('DRAWER.TITLE.FACEBOOK'),
onTap: () => {
launchURL('https://www.facebook.com/UniversidadeDoMindelo'),
}),
item(
icon: Icons.logout,
text: translate('DRAWER.TITLE.LOGOUT'),
onTap: () => {deleteData(user_uid), pushToView(loginRoute)}),
Divider(),
ListTile(
title: Text('v1.0.0'),
onTap: () {},
),
],
),
);
}
Widget header() {
return DrawerHeader(
margin: EdgeInsets.zero,
padding: EdgeInsets.zero,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.fill,
image: AssetImage('assets/images/logoHeader.jpg'))),
child: Stack(children: <Widget>[
Positioned(bottom: 12.0, left: 16.0, child: Text('')),
]));
}
Widget item(
{IconData? icon, required String text, GestureTapCallback? onTap}) {
return ListTile(
title: Row(
children: <Widget>[
Icon(icon),
Padding(
padding: EdgeInsets.only(left: 8.0),
child: Text(text),
)
],
),
onTap: onTap,
);
}
void pushToView(view) {
Navigator.pushNamed(context, view);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.