Explore all Mobile open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Mobile

NativeScript

@nativescript/core@8.2.2

vue-native-core

v0.3.1

nativescript-vue

ant-design-mobile-rn

4.2.0

KOOM

v2.0.0

Popular Libraries in Mobile

NativeScript

by NativeScript doticontypescriptdoticon

star image 21109 doticonMIT

⚡ Empowering JavaScript with native platform APIs. ✨ Best of all worlds (TypeScript, Swift, Objective C, Kotlin, Java). Use what you love ❤️ Angular, Capacitor, Ionic, React, Svelte, Vue and you name it compatible.

ratchet

by twbs doticoncssdoticon

star image 14471 doticonMIT

Build mobile apps with simple HTML, CSS, and JavaScript components.

incubator-weex

by apache doticonc++doticon

star image 14040 doticonApache-2.0

Apache Weex (Incubating)

amazeui

by amazeui doticonjavascriptdoticon

star image 13532 doticonNOASSERTION

Amaze UI, a mobile-first and modular front-end framework.

vue-native-core

by GeekyAnts doticonjavascriptdoticon

star image 8361 doticonMIT

Vue Native is a framework to build cross platform native mobile apps using JavaScript

mvt

by mvt-project doticonpythondoticon

star image 6869 doticonNOASSERTION

MVT (Mobile Verification Toolkit) helps with conducting forensics of mobile devices in order to find signs of a potential compromise.

SUI-Mobile

by sdc-alibaba doticonjavascriptdoticon

star image 6185 doticonMIT

SUI Mobile (MSUI)是由阿里巴巴国际UED前端出品的移动端UI库,轻量精美

nativescript-vue

by nativescript-vue doticonjavascriptdoticon

star image 4805 doticonMIT

Native mobile applications using Vue and NativeScript.

mobile-detect.js

by hgoebl doticonjavascriptdoticon

star image 3740 doticonMIT

Device detection (phone, tablet, desktop, mobile grade, os, versions)

Trending New libraries in Mobile

mvt

by mvt-project doticonpythondoticon

star image 6869 doticonNOASSERTION

MVT (Mobile Verification Toolkit) helps with conducting forensics of mobile devices in order to find signs of a potential compromise.

keen-slider

by rcbyr doticontypescriptdoticon

star image 3299 doticonMIT

The touch slider carousel with the most native feeling

KOOM

by KwaiAppTeam doticonc++doticon

star image 2354 doticonNOASSERTION

KOOM is an OOM killer on mobile platform by Kwai.

mobile-app-automizer

by automizer doticonjavascriptdoticon

star image 533 doticonMIT

You can automize iOS and Android app's build, upload and versioning processes via Mobile App Automizer CLI tool.

mobile-lpr

by xiangweizeng doticonc++doticon

star image 484 doticon

Mobile-LPR 是一个面向移动端的准商业级车牌识别库,以NCNN作为推理后端,使用DNN作为算法核心,支持多种车牌检测算法,支持车牌识别和车牌颜色识别。

UnityURP-MobileDrawMeshInstancedIndirectExample

by ColinLeung-NiloCat doticoncsharpdoticon

star image 474 doticonMIT

Example project to draw 1million grass instances on mobile

SpeedySwift

by Tliens doticonswiftdoticon

star image 317 doticonMIT

这是一个app开发的加速库。This is an accelerated library for app development

OkHttpLogger-Frida

by siyujie doticonjavascriptdoticon

star image 316 doticon

Frida 实现拦截okhttp的脚本

byopen

by hack0z doticoncdoticon

star image 172 doticonApache-2.0

🎉A dlopen library that bypasses mobile system limitation

Top Authors in Mobile

1

NativeScript

59 Libraries

star icon26989

2

EddyVerbruggen

29 Libraries

star icon1252

3

appcelerator-archive

26 Libraries

star icon900

4

AppWerft

25 Libraries

star icon149

5

aaronksaunders

25 Libraries

star icon301

6

triniwiz

23 Libraries

star icon451

7

NathanaelA

20 Libraries

star icon538

8

appcelerator-developer-relations

20 Libraries

star icon575

9

appcelerator

18 Libraries

star icon2914

10

NathanWalker

18 Libraries

star icon616

1

59 Libraries

star icon26989

2

29 Libraries

star icon1252

3

26 Libraries

star icon900

4

25 Libraries

star icon149

5

25 Libraries

star icon301

6

23 Libraries

star icon451

7

20 Libraries

star icon538

9

18 Libraries

star icon2914

10

18 Libraries

star icon616

Trending Kits in Mobile

No Trending Kits are available at this moment for Mobile

Trending Discussions on Mobile

App using Realtime database not working in Romania ISPs blocked by Firebase

Android studio - Generate signed APKs broke

Horizontal listview not scrolling on web but scrolling on mobile

Flutter iOS Error Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libamsupport.dylib (0x203913130)

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent, On AlarmPingSender

Android Build Error: "lStar not found..."

How do I get mobile status for discord bot by directly modifying IDENTIFY packet?

Data path "" must NOT have additional properties(extractCss) in Angular 13 while upgrading project

Flutter Web: Cannot scroll with mouse down (drag) (Flutter 2.5+)

clarity.js by Microsoft slowing overall page loads

QUESTION

App using Realtime database not working in Romania ISPs blocked by Firebase

Asked 2022-Mar-29 at 13:21

I'm facing a critical issue right now in Romania. So for almost 24 hours my mobile app which is using Firebase Realtime Database can't be used on some ISPs (like Vodafone, DIGI or Telekom) if you are using mobile data (4G or 5G) the app is working fine, but on Wi-fi (on these ISPs the app is getting timeout). I talked like several hours on the phone with multiple ISPs and the Firebase support (right now the app is working using DIGI, but nobody knows why). The ISPs are saying that problem is not on their end and Firebase is saying that the problem is on the ISP side. Firebase support answer:

As this has been caused by network issues, rather than Google's infrastructure, we can't do much about it from our end. I would recommend that you contact the ISP provider directly as they will be able to check deeper on their side.

As far as we can see, the multiple providers are affected by that issue. Our engineering team is already aware of that and looking for solutions. Like I said before, there is nothing we could do with the providers, but our engineers would find any suitable workaround.

So my question is: what can I do? (I saw that Firebase realtime database deployed in europe-west works) but mine is already on united states.

Is there someone having troubles like me? I tested multiple apps which I know are using Firebase and they are having the same issues, the app being unreachable over this type of network.

Updates on the issue: enter image description here

So the problem is regarding Ukraine and Russia :(. Many apps using Firebase Realtime Database are not working right now.

Below I posted a fix for this and how I handled in order to make my app functional again

ANSWER

Answered 2022-Mar-29 at 13:21

So for someone who is in Europe and has the same issue like me, this is what i did.

I made a new instance of a realtime database on europe-west (because this one works on every ISP). I migrated my old database to the new one. I pushed for release a new iOS and Android build using the new database. I disabled my old instance in order to not have any syncing problems. I made all of this at night hours like 24:00.

I the morning all users would have the new update. If someone is not going to have the update until 10 AM I have set a push notification to announce this changes.

Source https://stackoverflow.com/questions/71444553

QUESTION

Android studio - Generate signed APKs broke

Asked 2022-Mar-15 at 13:50

I just updated my Android studio to the version 2021.1.1 Canary 12. After struggling to make it work, I had to also upgrade my Gradle and Gradle plugin to 7.0.2. Now I can compile my project and launch my app on my mobile, everything is working. But when I try to generate a Signed APK, I get a strange message after building telling me: APK(s) generated successfully for module 'android-mobile-app-XXXX.app' with 0 build variants:

enter image description here

Even though the build seem to be successful I cannot find the generated APK anywhere (and considering the time it takes to give me that error, I don't even think it is building anything). Now, I have been generating an APK every week for years now, so I know my way around the folders, the different build variant output folders etc... Nothing changed in my way of generating an APK. I do it via AS and follow the very standard procedure.

Can someone point to me what am I missing here? I assume there is a way to select a specific build variant when generating a signed APK, how does it works?

PS: Obviously, I am selecting my variant here during the process: enter image description here

PS2: I can generate a debug APK without any issue whatsoever.

ANSWER

Answered 2021-Oct-05 at 07:39

After a few days of struggle, I ended up switching to Bundle. It achieves the same purpose for me and it actually works so... That's my solution here.

Source https://stackoverflow.com/questions/69408222

QUESTION

Horizontal listview not scrolling on web but scrolling on mobile

Asked 2022-Mar-02 at 19:02

After flutter 2.5 update listview is scrolling only on mobile platforms. It doesn't scroll when I open it on the web. It was working fine in the previous version. I tried the scroll physics but it didn't work. what do you suggest i do? sorry for my bad english.

1
2          return SizedBox(
3            height: 400,
4            child: ListView.builder(
5                physics: ClampingScrollPhysics(),
6                scrollDirection: Axis.horizontal,
7                // ignore: unnecessary_null_comparison
8                itemCount: items == null ? 0 : items.length,
9                itemBuilder: (context, index) {
10                  return GestureDetector(
11                      onTap: () {
12                        LoginForm();
13                      },
14                      child: Container(
15                        margin:
16                            EdgeInsets.symmetric(horizontal: 20, vertical: 6),
17                        child: SizedBox(
18                          width: 400,
19                          height: 50,
20                          child: Stack(
21                            fit: StackFit.expand,
22                            children: <Widget>[
23                              Container(
24                                decoration: BoxDecoration(
25                                    borderRadius:
26                                        BorderRadius.all(Radius.circular(20.0)),
27                                    boxShadow: [
28                                      BoxShadow(
29                                          color: fromCssColor(
30                                              items[index].color.toString()),
31                                          // color: Colors.black38,
32                                          offset: Offset(2.0, 2.0),
33                                          blurRadius: 5.0,
34                                          spreadRadius: 1.0)
35                                    ]),
36                              ),
37                              ClipRRect(
38                                borderRadius:
39                                    BorderRadius.all(Radius.circular(20.0)),
40                                child: Image.asset(
41                                  items[index].image.toString(),
42                                  fit: BoxFit.cover,
43                                ),
44                              ),
45                              Container(
46                                decoration: BoxDecoration(
47                                    borderRadius:
48                                        BorderRadius.all(Radius.circular(20.0)),
49                                    gradient: LinearGradient(
50                                        begin: Alignment.topCenter,
51                                        end: Alignment.bottomCenter,
52                                        colors: [
53                                          Colors.transparent,
54                                          Colors.black45
55                                        ]))
56                                    ),
57                                  ],
58                                ),
59                              ),
60                              
61

ANSWER

Answered 2022-Mar-02 at 19:02
Flutter 2.5 Summary

ScrollBehaviors now allow or disallow drag scrolling from specified PointerDeviceKinds. ScrollBehavior.dragDevices, by default, allows scrolling widgets to be dragged by all PointerDeviceKinds except for PointerDeviceKind.mouse.

1
2          return SizedBox(
3            height: 400,
4            child: ListView.builder(
5                physics: ClampingScrollPhysics(),
6                scrollDirection: Axis.horizontal,
7                // ignore: unnecessary_null_comparison
8                itemCount: items == null ? 0 : items.length,
9                itemBuilder: (context, index) {
10                  return GestureDetector(
11                      onTap: () {
12                        LoginForm();
13                      },
14                      child: Container(
15                        margin:
16                            EdgeInsets.symmetric(horizontal: 20, vertical: 6),
17                        child: SizedBox(
18                          width: 400,
19                          height: 50,
20                          child: Stack(
21                            fit: StackFit.expand,
22                            children: <Widget>[
23                              Container(
24                                decoration: BoxDecoration(
25                                    borderRadius:
26                                        BorderRadius.all(Radius.circular(20.0)),
27                                    boxShadow: [
28                                      BoxShadow(
29                                          color: fromCssColor(
30                                              items[index].color.toString()),
31                                          // color: Colors.black38,
32                                          offset: Offset(2.0, 2.0),
33                                          blurRadius: 5.0,
34                                          spreadRadius: 1.0)
35                                    ]),
36                              ),
37                              ClipRRect(
38                                borderRadius:
39                                    BorderRadius.all(Radius.circular(20.0)),
40                                child: Image.asset(
41                                  items[index].image.toString(),
42                                  fit: BoxFit.cover,
43                                ),
44                              ),
45                              Container(
46                                decoration: BoxDecoration(
47                                    borderRadius:
48                                        BorderRadius.all(Radius.circular(20.0)),
49                                    gradient: LinearGradient(
50                                        begin: Alignment.topCenter,
51                                        end: Alignment.bottomCenter,
52                                        colors: [
53                                          Colors.transparent,
54                                          Colors.black45
55                                        ]))
56                                    ),
57                                  ],
58                                ),
59                              ),
60                              
61import 'package:flutter/material.dart';
62
63// Set ScrollBehavior for an entire application.
64MaterialApp(
65  scrollBehavior: MyCustomScrollBehavior(),
66  // ...
67);
68
1
2          return SizedBox(
3            height: 400,
4            child: ListView.builder(
5                physics: ClampingScrollPhysics(),
6                scrollDirection: Axis.horizontal,
7                // ignore: unnecessary_null_comparison
8                itemCount: items == null ? 0 : items.length,
9                itemBuilder: (context, index) {
10                  return GestureDetector(
11                      onTap: () {
12                        LoginForm();
13                      },
14                      child: Container(
15                        margin:
16                            EdgeInsets.symmetric(horizontal: 20, vertical: 6),
17                        child: SizedBox(
18                          width: 400,
19                          height: 50,
20                          child: Stack(
21                            fit: StackFit.expand,
22                            children: <Widget>[
23                              Container(
24                                decoration: BoxDecoration(
25                                    borderRadius:
26                                        BorderRadius.all(Radius.circular(20.0)),
27                                    boxShadow: [
28                                      BoxShadow(
29                                          color: fromCssColor(
30                                              items[index].color.toString()),
31                                          // color: Colors.black38,
32                                          offset: Offset(2.0, 2.0),
33                                          blurRadius: 5.0,
34                                          spreadRadius: 1.0)
35                                    ]),
36                              ),
37                              ClipRRect(
38                                borderRadius:
39                                    BorderRadius.all(Radius.circular(20.0)),
40                                child: Image.asset(
41                                  items[index].image.toString(),
42                                  fit: BoxFit.cover,
43                                ),
44                              ),
45                              Container(
46                                decoration: BoxDecoration(
47                                    borderRadius:
48                                        BorderRadius.all(Radius.circular(20.0)),
49                                    gradient: LinearGradient(
50                                        begin: Alignment.topCenter,
51                                        end: Alignment.bottomCenter,
52                                        colors: [
53                                          Colors.transparent,
54                                          Colors.black45
55                                        ]))
56                                    ),
57                                  ],
58                                ),
59                              ),
60                              
61import 'package:flutter/material.dart';
62
63// Set ScrollBehavior for an entire application.
64MaterialApp(
65  scrollBehavior: MyCustomScrollBehavior(),
66  // ...
67);
68import 'package:flutter/gestures.dart';
69import 'package:flutter/material.dart';
70
71class MyCustomScrollBehavior extends MaterialScrollBehavior {
72  // Override behavior methods and getters like dragDevices
73  @override
74  Set<PointerDeviceKind> get dragDevices => {
75        PointerDeviceKind.touch,
76        PointerDeviceKind.mouse,
77      };
78}
79

Source https://stackoverflow.com/questions/69154468

QUESTION

Flutter iOS Error Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libamsupport.dylib (0x203913130)

Asked 2022-Mar-01 at 05:29

Hi am facing an issue while running flutter project in MacBook Air M1 chip Lap. Tried all possibilities couldn't find where is the exact problem.

All basic solutions like flutter clean, flutter pub get, pod deintegrate & install, flutter build ios, flutter run but still same issue. only on iOS simulator not deploying.

Any solution for this. Thanks in advance.

Error

1Launching lib/main.dart on iPhone 13 in debug mode...
2Running pod install...                                              5.3s
3Running Xcode build...                                                  
4Xcode build done.                                           104.1s
5Failed to build iOS app
6Error output from Xcode build:
78    objc[25282]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libamsupport.dylib (0x203913130) and
9    /Library/Apple/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x103bc02c8). One of the two will be used. Which one is undefined.
10    objc[25282]: Class AMSupportURLSession is implemented in both /usr/lib/libamsupport.dylib (0x203913180) and
11    /Library/Apple/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x103bc0318). One of the two will be used. Which one is undefined.
12    ** BUILD FAILED **
13

flutter doctor -v

1Launching lib/main.dart on iPhone 13 in debug mode...
2Running pod install...                                              5.3s
3Running Xcode build...                                                  
4Xcode build done.                                           104.1s
5Failed to build iOS app
6Error output from Xcode build:
78    objc[25282]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libamsupport.dylib (0x203913130) and
9    /Library/Apple/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x103bc02c8). One of the two will be used. Which one is undefined.
10    objc[25282]: Class AMSupportURLSession is implemented in both /usr/lib/libamsupport.dylib (0x203913180) and
11    /Library/Apple/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x103bc0318). One of the two will be used. Which one is undefined.
12    ** BUILD FAILED **
13[✓] Flutter (Channel stable, 2.8.1, on macOS 12.0.1 21A559 darwin-arm, locale
14    en-IN)
15    • Flutter version 2.8.1 at
16      /Users/macsystem/Documents/developer/flutter
17    • Upstream repository https://github.com/flutter/flutter.git
18    • Framework revision 77d935af4d (7 weeks ago), 2021-12-16 08:37:33 -0800
19    • Engine revision 890a5fca2e
20    • Dart version 2.15.1
21
22[✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
23    • Android SDK at /Users/macsystem/Library/Android/sdk
24    • Platform android-32, build-tools 32.0.0
25    • Java binary at: /Applications/Android
26      Studio.app/Contents/jre/Contents/Home/bin/java
27    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
28    • All Android licenses accepted.
29
30[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
31    • Xcode at /Applications/Xcode.app/Contents/Developer
32    • CocoaPods version 1.11.2
33
34[✓] Chrome - develop for the web
35    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
36
37[✓] Android Studio (version 2020.3)
38    • Android Studio at /Applications/Android Studio.app/Contents
39    • Flutter plugin can be installed from:
40      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
41    • Dart plugin can be installed from:
42      🔨 https://plugins.jetbrains.com/plugin/6351-dart
43    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
44
45[✓] Connected device (2 available)
46    • iPhone 13 (mobile) • 05EC9698-3C26-44B9-8DB0-B53C7B6576F3 • ios
47      • com.apple.CoreSimulator.SimRuntime.iOS-15-2 (simulator)
48    • Chrome (web)       • chrome                               • web-javascript
49      • Google Chrome 97.0.4692.99
50

ANSWER

Answered 2022-Feb-02 at 04:43

I have been facing this same issue for some time now. the same setup is working nicely in a mac with intel chip. But i have even done a resetup of my system, m1 mac still throws the same error.

Source https://stackoverflow.com/questions/70936334

QUESTION

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent, On AlarmPingSender

Asked 2022-Feb-20 at 16:06
Problem

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. I got it after updating target SDK to 31. the error always come after AlarmPingSender. But i dont know any class that used AlarmPingSender.

1
22021-10-31 10:43:04.990 17031-17341/com.app.mobile D/AlarmPingSender: Register alarmreceiver to MqttServiceMqttService.pingSender.com.app.mobile-2e24ccbde048f2e91635651784
32021-10-31 10:43:04.993 17031-17341/com.app.mobile E/AndroidRuntime: FATAL EXCEPTION: MQTT Rec: com.app.mobile-2e24ccbde048f2e91635651784
4    Process: com.app.mobile, PID: 17031
5    java.lang.IllegalArgumentException: com.app.mobile: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
6    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
7        at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
8        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645)
9        at android.app.PendingIntent.getBroadcast(PendingIntent.java:632)
10        at org.eclipse.paho.android.service.AlarmPingSender.start(AlarmPingSender.java:76)
11        at org.eclipse.paho.client.mqttv3.internal.ClientState.connected(ClientState.java:1150)
12        at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:987)
13        at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:118)
14        at java.lang.Thread.run(Thread.java:920)
15
16
What I Already done
  • Upgrade WorkManager to 2.7.0
  • set AllProject to force use WorkManager to 2.7.0
  • change all existing PendingIntent to use FLAG_IMMUTABLE
  • there's old code that still use gcm and disable it
  • Updating all Firebase package (some said its because of later version of analytics)
Library Used
  • OneSignal
  • Qiscus
  • Firebase
  • WorkManager

ANSWER

Answered 2021-Oct-31 at 07:02

Possible solution

Upgrade google analytics to firebase analaytics. Hope it'll solve your problems.Also upgrade all the library what're you using.

For me below solutions solve the problem.

Add PendingIntent.FLAG_IMMUTABLE to your pending intents.

Here is an example -

PendingIntent pendingIntent = PendingIntent.getActivity(this, alarmID, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

For further information follow this link - https://developer.android.com/reference/android/app/PendingIntent#FLAG_IMMUTABLE

Source https://stackoverflow.com/questions/69783824

QUESTION

Android Build Error: "lStar not found..."

Asked 2022-Feb-18 at 06:59

I have error like this after trying to build my apps in Emulator

/Users/joel/.gradle/caches/transforms-3/06231cc1265260b25a06bafce7a4176f/transformed/core-1.7.0-alpha02/res/values/values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.

I don't know what causes this error. After digging some answer which has similarly error (but in flutter) Problem. But still not solved my issue.

I have this dependency in my project

1buildscript {
2    repositories {
3        google()
4        maven { url 'https://plugins.gradle.org/m2/' }
5    }
6
7    dependencies {
8        classpath 'com.google.gms:google-services:4.3.3'
9        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0'
10    }
11}
12apply plugin: 'com.android.application'
13apply plugin: 'com.google.gms.google-services'
14apply plugin: 'kotlin-android'
15apply plugin: 'kotlin-android-extensions'
16apply plugin: 'kotlin-kapt'
17apply plugin: 'com.google.firebase.crashlytics'
18
19repositories {
20    maven { url 'https://maven.fabric.io/public' }
21    maven { url 'https://maven.google.com' }
22    maven { url  "https://teads.jfrog.io/artifactory/SDKAndroid-maven-prod"}
23    mavenCentral()
24
25}
26
27android {
28    compileSdkVersion 29
29    buildToolsVersion '28.0.3'
30    defaultConfig {
31        applicationId "mobile.apps.my"
32        minSdkVersion 17
33        targetSdkVersion 29
34        multiDexEnabled true
35        versionCode 152
36        versionName "8.1.7"
37        vectorDrawables.useSupportLibrary = true // This line hereP
38        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
39    }
40
41    compileOptions {
42        sourceCompatibility JavaVersion.VERSION_1_8
43        targetCompatibility JavaVersion.VERSION_1_8
44    }
45
46    dataBinding {
47        enabled = true
48    }
49
50    buildTypes {
51        debug {
52            firebaseCrashlytics {
53                mappingFileUploadEnabled false
54            }
55        }
56
57        release {
58            minifyEnabled true
59            shrinkResources true
60            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
61        }
62    }
63
64    lintOptions {
65        checkReleaseBuilds false
66        abortOnError false
67    }
68}
69
70dependencies {
71
72    implementation fileTree(include: ['*.jar'], dir: 'libs')
73    androidTestImplementation('androidx.test.espresso:espresso-core:3.2.0-beta01', {
74        exclude group: 'com.android.support', module: 'support-annotations'
75    })
76    //noinspection GradleCompatible
77    implementation 'androidx.appcompat:appcompat:1.4.0-alpha03'
78    implementation "androidx.appcompat:appcompat-resources:1.4.0-alpha03"
79
80    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
81    implementation 'androidx.preference:preference:1.1.1'
82    implementation 'com.google.android.material:material:1.4.0'
83    implementation 'androidx.recyclerview:recyclerview:1.2.1'
84    implementation 'androidx.cardview:cardview:1.0.0'
85    implementation 'androidx.percentlayout:percentlayout:1.0.0'
86
87    implementation 'com.google.android.gms:play-services-analytics:17.0.0'
88    implementation 'it.sephiroth.android.library.imagezoom:imagezoom:2.3.0'
89    testImplementation 'org.json:json:20140107'
90    implementation 'com.comscore:android-analytics:6.1.0'
91    implementation 'com.android.support:customtabs:29.0.0'
92    implementation 'androidx.viewpager2:viewpager2:1.0.0'
93    implementation 'com.android.support:customtabs:29.0.0'
94
95    // Kodein Dependency Injection
96    implementation 'org.kodein.di:kodein-di-generic-jvm:6.2.1'
97    implementation 'org.kodein.di:kodein-di-framework-android-x:6.2.1'
98
99    // RETROFIT
100    implementation 'com.squareup.retrofit2:retrofit:2.6.0'
101    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
102    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
103    implementation 'com.google.code.gson:gson:2.8.5'
104    implementation 'com.squareup.retrofit2:converter-scalars:2.1.0' // for test String
105
106
107    // Room components
108    implementation "androidx.room:room-runtime:2.2.5"
109    kapt "androidx.room:room-compiler:2.2.5"
110    implementation "androidx.room:room-ktx:2.2.5"
111    androidTestImplementation "androidx.room:room-testing:2.2.5"
112
113    // Lifecycle components
114    implementation 'android.arch.lifecycle:extensions:1.1.1'
115    implementation 'androidx.paging:paging-runtime:2.1.2'
116
117    // UI
118    implementation 'com.squareup.picasso:picasso:2.71828'
119    implementation 'com.geniusforapp.fancydialog:FancyDialog:0.1.4'
120    implementation 'com.github.bluzwong:swipeback:0.2.0@aar'
121    implementation 'com.airbnb.android:lottie:3.6.0'
122
123    implementation 'com.veinhorn.scrollgalleryview:library:1.2.6'
124    implementation 'com.veinhorn.scrollgalleryview:picasso-loader:1.2.4'
125    implementation 'com.github.rubensousa:bottomsheetbuilder:1.6.1'
126    implementation "com.andkulikov:transitionseverywhere:1.8.1"
127
128
129    // HTTP LOGGING
130    implementation 'com.jakewharton.timber:timber:4.7.1'
131    implementation 'org.jsoup:jsoup:1.13.1'
132    implementation 'androidx.multidex:multidex:2.0.1'
133
134
135    // ADS
136    implementation 'com.android.support:support-annotations:28.0.0'
137    // Required Dependency by Audience Network SDK
138    implementation 'com.google.android.gms:play-services-ads:19.7.0'
139    implementation 'com.google.android.gms:play-services-basement:17.6.0'
140    implementation("tv.teads.sdk.android:sdk:4.7.2@aar") {
141        transitive = true
142    }
143    implementation 'com.criteo.publisher:criteo-publisher-sdk:4.0.0'
144    implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'
145    implementation 'com.google.android.gms:play-services-base:17.6.0'
146
147    implementation ('com.facebook.android:audience-network-sdk:5.5.0'){
148        exclude group: 'com.google.android.gms'
149    }
150
151    implementation 'com.google.firebase:firebase-crashlytics:17.4.0'
152
153    implementation "androidx.core:core-ktx:1.6.0"  // I have update this based on other solution
154    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
155    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
156
157    // COROUTINES
158    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1'
159    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
160    implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
161
162    // Kotlin + coroutines
163    implementation "androidx.work:work-runtime-ktx:2.5.0"
164
165    implementation 'com.github.mumayank:AirLocation:1.3.1'
166    androidTestImplementation 'androidx.test:rules:1.3.0-beta01'
167
168    implementation 'com.android.installreferrer:installreferrer:2.2'
169
170    //ANIMATION
171    implementation 'com.daimajia.androidanimations:library:2.4@aar'
172    implementation 'com.infideap.drawerbehavior:drawer-behavior:1.0.4'
173    implementation 'com.romandanylyk:pageindicatorview:1.0.3'
174
175    implementation 'org.ocpsoft.prettytime:prettytime:5.0.0.Final'
176
177    //SOCIAL
178    implementation 'com.google.android.gms:play-services-auth:19.0.0'
179
180}
181

I have tried to upgrade version of androidx.core:core-ktx:1.6.0 then sync or invalidate cache/restart. But none of them give me good result. I am sure yesterday my project was alright with same dependency. Someone please help me, if this question unclear let me add more information. Thanks

ANSWER

Answered 2021-Sep-28 at 17:18

I managed to fix this by upgrading compileSdk to 31 and kotlin gradle plugin to 1.5.10

1buildscript {
2    repositories {
3        google()
4        maven { url 'https://plugins.gradle.org/m2/' }
5    }
6
7    dependencies {
8        classpath 'com.google.gms:google-services:4.3.3'
9        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0'
10    }
11}
12apply plugin: 'com.android.application'
13apply plugin: 'com.google.gms.google-services'
14apply plugin: 'kotlin-android'
15apply plugin: 'kotlin-android-extensions'
16apply plugin: 'kotlin-kapt'
17apply plugin: 'com.google.firebase.crashlytics'
18
19repositories {
20    maven { url 'https://maven.fabric.io/public' }
21    maven { url 'https://maven.google.com' }
22    maven { url  "https://teads.jfrog.io/artifactory/SDKAndroid-maven-prod"}
23    mavenCentral()
24
25}
26
27android {
28    compileSdkVersion 29
29    buildToolsVersion '28.0.3'
30    defaultConfig {
31        applicationId "mobile.apps.my"
32        minSdkVersion 17
33        targetSdkVersion 29
34        multiDexEnabled true
35        versionCode 152
36        versionName "8.1.7"
37        vectorDrawables.useSupportLibrary = true // This line hereP
38        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
39    }
40
41    compileOptions {
42        sourceCompatibility JavaVersion.VERSION_1_8
43        targetCompatibility JavaVersion.VERSION_1_8
44    }
45
46    dataBinding {
47        enabled = true
48    }
49
50    buildTypes {
51        debug {
52            firebaseCrashlytics {
53                mappingFileUploadEnabled false
54            }
55        }
56
57        release {
58            minifyEnabled true
59            shrinkResources true
60            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
61        }
62    }
63
64    lintOptions {
65        checkReleaseBuilds false
66        abortOnError false
67    }
68}
69
70dependencies {
71
72    implementation fileTree(include: ['*.jar'], dir: 'libs')
73    androidTestImplementation('androidx.test.espresso:espresso-core:3.2.0-beta01', {
74        exclude group: 'com.android.support', module: 'support-annotations'
75    })
76    //noinspection GradleCompatible
77    implementation 'androidx.appcompat:appcompat:1.4.0-alpha03'
78    implementation "androidx.appcompat:appcompat-resources:1.4.0-alpha03"
79
80    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
81    implementation 'androidx.preference:preference:1.1.1'
82    implementation 'com.google.android.material:material:1.4.0'
83    implementation 'androidx.recyclerview:recyclerview:1.2.1'
84    implementation 'androidx.cardview:cardview:1.0.0'
85    implementation 'androidx.percentlayout:percentlayout:1.0.0'
86
87    implementation 'com.google.android.gms:play-services-analytics:17.0.0'
88    implementation 'it.sephiroth.android.library.imagezoom:imagezoom:2.3.0'
89    testImplementation 'org.json:json:20140107'
90    implementation 'com.comscore:android-analytics:6.1.0'
91    implementation 'com.android.support:customtabs:29.0.0'
92    implementation 'androidx.viewpager2:viewpager2:1.0.0'
93    implementation 'com.android.support:customtabs:29.0.0'
94
95    // Kodein Dependency Injection
96    implementation 'org.kodein.di:kodein-di-generic-jvm:6.2.1'
97    implementation 'org.kodein.di:kodein-di-framework-android-x:6.2.1'
98
99    // RETROFIT
100    implementation 'com.squareup.retrofit2:retrofit:2.6.0'
101    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
102    implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
103    implementation 'com.google.code.gson:gson:2.8.5'
104    implementation 'com.squareup.retrofit2:converter-scalars:2.1.0' // for test String
105
106
107    // Room components
108    implementation "androidx.room:room-runtime:2.2.5"
109    kapt "androidx.room:room-compiler:2.2.5"
110    implementation "androidx.room:room-ktx:2.2.5"
111    androidTestImplementation "androidx.room:room-testing:2.2.5"
112
113    // Lifecycle components
114    implementation 'android.arch.lifecycle:extensions:1.1.1'
115    implementation 'androidx.paging:paging-runtime:2.1.2'
116
117    // UI
118    implementation 'com.squareup.picasso:picasso:2.71828'
119    implementation 'com.geniusforapp.fancydialog:FancyDialog:0.1.4'
120    implementation 'com.github.bluzwong:swipeback:0.2.0@aar'
121    implementation 'com.airbnb.android:lottie:3.6.0'
122
123    implementation 'com.veinhorn.scrollgalleryview:library:1.2.6'
124    implementation 'com.veinhorn.scrollgalleryview:picasso-loader:1.2.4'
125    implementation 'com.github.rubensousa:bottomsheetbuilder:1.6.1'
126    implementation "com.andkulikov:transitionseverywhere:1.8.1"
127
128
129    // HTTP LOGGING
130    implementation 'com.jakewharton.timber:timber:4.7.1'
131    implementation 'org.jsoup:jsoup:1.13.1'
132    implementation 'androidx.multidex:multidex:2.0.1'
133
134
135    // ADS
136    implementation 'com.android.support:support-annotations:28.0.0'
137    // Required Dependency by Audience Network SDK
138    implementation 'com.google.android.gms:play-services-ads:19.7.0'
139    implementation 'com.google.android.gms:play-services-basement:17.6.0'
140    implementation("tv.teads.sdk.android:sdk:4.7.2@aar") {
141        transitive = true
142    }
143    implementation 'com.criteo.publisher:criteo-publisher-sdk:4.0.0'
144    implementation 'com.google.android.gms:play-services-ads-identifier:17.0.0'
145    implementation 'com.google.android.gms:play-services-base:17.6.0'
146
147    implementation ('com.facebook.android:audience-network-sdk:5.5.0'){
148        exclude group: 'com.google.android.gms'
149    }
150
151    implementation 'com.google.firebase:firebase-crashlytics:17.4.0'
152
153    implementation "androidx.core:core-ktx:1.6.0"  // I have update this based on other solution
154    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
155    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
156
157    // COROUTINES
158    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1'
159    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'
160    implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
161
162    // Kotlin + coroutines
163    implementation "androidx.work:work-runtime-ktx:2.5.0"
164
165    implementation 'com.github.mumayank:AirLocation:1.3.1'
166    androidTestImplementation 'androidx.test:rules:1.3.0-beta01'
167
168    implementation 'com.android.installreferrer:installreferrer:2.2'
169
170    //ANIMATION
171    implementation 'com.daimajia.androidanimations:library:2.4@aar'
172    implementation 'com.infideap.drawerbehavior:drawer-behavior:1.0.4'
173    implementation 'com.romandanylyk:pageindicatorview:1.0.3'
174
175    implementation 'org.ocpsoft.prettytime:prettytime:5.0.0.Final'
176
177    //SOCIAL
178    implementation 'com.google.android.gms:play-services-auth:19.0.0'
179
180}
181compileSdk = 31
182
183classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10'
184

Source https://stackoverflow.com/questions/69041630

QUESTION

How do I get mobile status for discord bot by directly modifying IDENTIFY packet?

Asked 2022-Feb-09 at 15:05

Apparently, discord bots can have mobile status as opposed to the desktop (online) status that one gets by default.

bot having mobile status

After a bit of digging I found out that such a status is achieved by modifying the IDENTIFY packet in discord.gateway.DiscordWebSocket.identify modifying the value of $browser to Discord Android or Discord iOS should theoretically get us the mobile status.

After modifying code snippets I found online which does this, I end up with this :

1def get_mobile():
2    """
3    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
4    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
5    from there they send the extended presence object.
6    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
7    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
8    the mobile indicator is not triggered by the mobile client.
9    The specific values for the $os, $browser, and $device fields are can change from time to time.
10    """
11    import ast
12    import inspect
13    import re
14    import discord
15
16    def source(o):
17        s = inspect.getsource(o).split("\n")
18        indent = len(s[0]) - len(s[0].lstrip())
19
20        return "\n".join(i[indent:] for i in s)
21
22    source_ = source(discord.gateway.DiscordWebSocket.identify)
23    patched = re.sub(
24        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
25        r"\1Discord Android\2",
26        source_,
27    )
28
29    loc = {}
30    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
31    return loc["identify"]
32

Now all there is left to do is overwrite the discord.gateway.DiscordWebSocket.identify during runtime in the main file, something like this :

1def get_mobile():
2    """
3    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
4    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
5    from there they send the extended presence object.
6    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
7    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
8    the mobile indicator is not triggered by the mobile client.
9    The specific values for the $os, $browser, and $device fields are can change from time to time.
10    """
11    import ast
12    import inspect
13    import re
14    import discord
15
16    def source(o):
17        s = inspect.getsource(o).split("\n")
18        indent = len(s[0]) - len(s[0].lstrip())
19
20        return "\n".join(i[indent:] for i in s)
21
22    source_ = source(discord.gateway.DiscordWebSocket.identify)
23    patched = re.sub(
24        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
25        r"\1Discord Android\2",
26        source_,
27    )
28
29    loc = {}
30    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
31    return loc["identify"]
32import discord
33import os
34from discord.ext import commands
35import mobile_status
36
37discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
38bot = commands.Bot(command_prefix="?")
39
40@bot.event
41async def on_ready():
42    print(f"Sucessfully logged in as {bot.user}")
43
44bot.run(os.getenv("DISCORD_TOKEN"))
45

And we do get the mobile status successfully
successful mobile status for bot

But here's the problem, I wanted to directly modify the file (which held the function) rather than monkey-patching it during runtime. So I cloned the dpy lib locally and edited the file on my machine, it ended up looking like this :

1def get_mobile():
2    """
3    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
4    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
5    from there they send the extended presence object.
6    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
7    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
8    the mobile indicator is not triggered by the mobile client.
9    The specific values for the $os, $browser, and $device fields are can change from time to time.
10    """
11    import ast
12    import inspect
13    import re
14    import discord
15
16    def source(o):
17        s = inspect.getsource(o).split("\n")
18        indent = len(s[0]) - len(s[0].lstrip())
19
20        return "\n".join(i[indent:] for i in s)
21
22    source_ = source(discord.gateway.DiscordWebSocket.identify)
23    patched = re.sub(
24        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
25        r"\1Discord Android\2",
26        source_,
27    )
28
29    loc = {}
30    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
31    return loc["identify"]
32import discord
33import os
34from discord.ext import commands
35import mobile_status
36
37discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
38bot = commands.Bot(command_prefix="?")
39
40@bot.event
41async def on_ready():
42    print(f"Sucessfully logged in as {bot.user}")
43
44bot.run(os.getenv("DISCORD_TOKEN"))
45    async def identify(self):
46        """Sends the IDENTIFY packet."""
47        payload = {
48            'op': self.IDENTIFY,
49            'd': {
50                'token': self.token,
51                'properties': {
52                    '$os': sys.platform,
53                    '$browser': 'Discord Android',
54                    '$device': 'Discord Android',
55                    '$referrer': '',
56                    '$referring_domain': ''
57                },
58                'compress': True,
59                'large_threshold': 250,
60                'v': 3
61            }
62        }
63     # ...
64

(edited both $browser and $device to Discord Android just to be safe)

But this does not work and just gives me the regular desktop online icon.
So the next thing I did is to inspect the identify function after it has been monkey-patched, so I could just look at the source code and see what went wrong earlier, but due to hard luck I got this error :

1def get_mobile():
2    """
3    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
4    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
5    from there they send the extended presence object.
6    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
7    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
8    the mobile indicator is not triggered by the mobile client.
9    The specific values for the $os, $browser, and $device fields are can change from time to time.
10    """
11    import ast
12    import inspect
13    import re
14    import discord
15
16    def source(o):
17        s = inspect.getsource(o).split("\n")
18        indent = len(s[0]) - len(s[0].lstrip())
19
20        return "\n".join(i[indent:] for i in s)
21
22    source_ = source(discord.gateway.DiscordWebSocket.identify)
23    patched = re.sub(
24        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
25        r"\1Discord Android\2",
26        source_,
27    )
28
29    loc = {}
30    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
31    return loc["identify"]
32import discord
33import os
34from discord.ext import commands
35import mobile_status
36
37discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
38bot = commands.Bot(command_prefix="?")
39
40@bot.event
41async def on_ready():
42    print(f"Sucessfully logged in as {bot.user}")
43
44bot.run(os.getenv("DISCORD_TOKEN"))
45    async def identify(self):
46        """Sends the IDENTIFY packet."""
47        payload = {
48            'op': self.IDENTIFY,
49            'd': {
50                'token': self.token,
51                'properties': {
52                    '$os': sys.platform,
53                    '$browser': 'Discord Android',
54                    '$device': 'Discord Android',
55                    '$referrer': '',
56                    '$referring_domain': ''
57                },
58                'compress': True,
59                'large_threshold': 250,
60                'v': 3
61            }
62        }
63     # ...
64Traceback (most recent call last):
65  File "c:\Users\Achxy\Desktop\fresh\file.py", line 8, in <module>
66    print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
67  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1024, in getsource
68    lines, lnum = getsourcelines(object)
69  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1006, in getsourcelines
70    lines, lnum = findsource(object)
71  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 835, in findsource
72    raise OSError('could not get source code')
73OSError: could not get source code
74

Code :

1def get_mobile():
2    """
3    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
4    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
5    from there they send the extended presence object.
6    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
7    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
8    the mobile indicator is not triggered by the mobile client.
9    The specific values for the $os, $browser, and $device fields are can change from time to time.
10    """
11    import ast
12    import inspect
13    import re
14    import discord
15
16    def source(o):
17        s = inspect.getsource(o).split("\n")
18        indent = len(s[0]) - len(s[0].lstrip())
19
20        return "\n".join(i[indent:] for i in s)
21
22    source_ = source(discord.gateway.DiscordWebSocket.identify)
23    patched = re.sub(
24        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
25        r"\1Discord Android\2",
26        source_,
27    )
28
29    loc = {}
30    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
31    return loc["identify"]
32import discord
33import os
34from discord.ext import commands
35import mobile_status
36
37discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
38bot = commands.Bot(command_prefix="?")
39
40@bot.event
41async def on_ready():
42    print(f"Sucessfully logged in as {bot.user}")
43
44bot.run(os.getenv("DISCORD_TOKEN"))
45    async def identify(self):
46        """Sends the IDENTIFY packet."""
47        payload = {
48            'op': self.IDENTIFY,
49            'd': {
50                'token': self.token,
51                'properties': {
52                    '$os': sys.platform,
53                    '$browser': 'Discord Android',
54                    '$device': 'Discord Android',
55                    '$referrer': '',
56                    '$referring_domain': ''
57                },
58                'compress': True,
59                'large_threshold': 250,
60                'v': 3
61            }
62        }
63     # ...
64Traceback (most recent call last):
65  File "c:\Users\Achxy\Desktop\fresh\file.py", line 8, in <module>
66    print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
67  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1024, in getsource
68    lines, lnum = getsourcelines(object)
69  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1006, in getsourcelines
70    lines, lnum = findsource(object)
71  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 835, in findsource
72    raise OSError('could not get source code')
73OSError: could not get source code
74import discord
75import os
76from discord.ext import commands
77import mobile_status
78import inspect
79
80discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
81print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
82bot = commands.Bot(command_prefix="?")
83
84@bot.event
85async def on_ready():
86    print(f"Sucessfully logged in as {bot.user}")
87
88bot.run(os.getenv("DISCORD_TOKEN"))
89

Since this same behavior was exhibited for every patched function (aforementioned one and the loc["identify"]) I could no longer use inspect.getsource(...) and then relied upon dis.dis which lead to much more disappointing results

The disassembled data looks exactly identical to the monkey-patched working version, so the directly modified version simply does not work despite function content being the exact same. (In regards to disassembled data)

Notes: Doing Discord iOS directly does not work either, changing the $device to some other value but keeping $browser does not work, I have tried all combinations, none of them work.

TL;DR: How to get mobile status for discord bot without monkey-patching it during runtime?

ANSWER

Answered 2022-Feb-07 at 23:03

The following works by subclassing the relevant class, and duplicating code with the relevant changes. We also have to subclass the Client class, to overwrite the place where the gateway/websocket class is used. This results in a lot of duplicated code, however it does work, and requires neither dirty monkey-patching nor editing the library source code.

However, it does come with many of the same problems as editing the library source code - mainly that as the library is updated, this code will become out of date (if you're using the archived and obsolete version of the library, you have bigger problems instead).

1def get_mobile():
2    """
3    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
4    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
5    from there they send the extended presence object.
6    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
7    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
8    the mobile indicator is not triggered by the mobile client.
9    The specific values for the $os, $browser, and $device fields are can change from time to time.
10    """
11    import ast
12    import inspect
13    import re
14    import discord
15
16    def source(o):
17        s = inspect.getsource(o).split("\n")
18        indent = len(s[0]) - len(s[0].lstrip())
19
20        return "\n".join(i[indent:] for i in s)
21
22    source_ = source(discord.gateway.DiscordWebSocket.identify)
23    patched = re.sub(
24        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
25        r"\1Discord Android\2",
26        source_,
27    )
28
29    loc = {}
30    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
31    return loc["identify"]
32import discord
33import os
34from discord.ext import commands
35import mobile_status
36
37discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
38bot = commands.Bot(command_prefix="?")
39
40@bot.event
41async def on_ready():
42    print(f"Sucessfully logged in as {bot.user}")
43
44bot.run(os.getenv("DISCORD_TOKEN"))
45    async def identify(self):
46        """Sends the IDENTIFY packet."""
47        payload = {
48            'op': self.IDENTIFY,
49            'd': {
50                'token': self.token,
51                'properties': {
52                    '$os': sys.platform,
53                    '$browser': 'Discord Android',
54                    '$device': 'Discord Android',
55                    '$referrer': '',
56                    '$referring_domain': ''
57                },
58                'compress': True,
59                'large_threshold': 250,
60                'v': 3
61            }
62        }
63     # ...
64Traceback (most recent call last):
65  File "c:\Users\Achxy\Desktop\fresh\file.py", line 8, in <module>
66    print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
67  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1024, in getsource
68    lines, lnum = getsourcelines(object)
69  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1006, in getsourcelines
70    lines, lnum = findsource(object)
71  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 835, in findsource
72    raise OSError('could not get source code')
73OSError: could not get source code
74import discord
75import os
76from discord.ext import commands
77import mobile_status
78import inspect
79
80discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
81print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
82bot = commands.Bot(command_prefix="?")
83
84@bot.event
85async def on_ready():
86    print(f"Sucessfully logged in as {bot.user}")
87
88bot.run(os.getenv("DISCORD_TOKEN"))
89import asyncio
90import sys
91
92import aiohttp
93
94import discord
95from discord.gateway import DiscordWebSocket, _log
96from discord.ext.commands import Bot
97
98
99class MyGateway(DiscordWebSocket):
100
101    async def identify(self):
102        payload = {
103            'op': self.IDENTIFY,
104            'd': {
105                'token': self.token,
106                'properties': {
107                    '$os': sys.platform,
108                    '$browser': 'Discord Android',
109                    '$device': 'Discord Android',
110                    '$referrer': '',
111                    '$referring_domain': ''
112                },
113                'compress': True,
114                'large_threshold': 250,
115                'v': 3
116            }
117        }
118
119        if self.shard_id is not None and self.shard_count is not None:
120            payload['d']['shard'] = [self.shard_id, self.shard_count]
121
122        state = self._connection
123        if state._activity is not None or state._status is not None:
124            payload['d']['presence'] = {
125                'status': state._status,
126                'game': state._activity,
127                'since': 0,
128                'afk': False
129            }
130
131        if state._intents is not None:
132            payload['d']['intents'] = state._intents.value
133
134        await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
135        await self.send_as_json(payload)
136        _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
137
138
139class MyBot(Bot):
140
141    async def connect(self, *, reconnect: bool = True) -> None:
142        """|coro|
143
144        Creates a websocket connection and lets the websocket listen
145        to messages from Discord. This is a loop that runs the entire
146        event system and miscellaneous aspects of the library. Control
147        is not resumed until the WebSocket connection is terminated.
148
149        Parameters
150        -----------
151        reconnect: :class:`bool`
152            If we should attempt reconnecting, either due to internet
153            failure or a specific failure on Discord's part. Certain
154            disconnects that lead to bad state will not be handled (such as
155            invalid sharding payloads or bad tokens).
156
157        Raises
158        -------
159        :exc:`.GatewayNotFound`
160            If the gateway to connect to Discord is not found. Usually if this
161            is thrown then there is a Discord API outage.
162        :exc:`.ConnectionClosed`
163            The websocket connection has been terminated.
164        """
165
166        backoff = discord.client.ExponentialBackoff()
167        ws_params = {
168            'initial': True,
169            'shard_id': self.shard_id,
170        }
171        while not self.is_closed():
172            try:
173                coro = MyGateway.from_client(self, **ws_params)
174                self.ws = await asyncio.wait_for(coro, timeout=60.0)
175                ws_params['initial'] = False
176                while True:
177                    await self.ws.poll_event()
178            except discord.client.ReconnectWebSocket as e:
179                _log.info('Got a request to %s the websocket.', e.op)
180                self.dispatch('disconnect')
181                ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)
182                continue
183            except (OSError,
184                    discord.HTTPException,
185                    discord.GatewayNotFound,
186                    discord.ConnectionClosed,
187                    aiohttp.ClientError,
188                    asyncio.TimeoutError) as exc:
189
190                self.dispatch('disconnect')
191                if not reconnect:
192                    await self.close()
193                    if isinstance(exc, discord.ConnectionClosed) and exc.code == 1000:
194                        # clean close, don't re-raise this
195                        return
196                    raise
197
198                if self.is_closed():
199                    return
200
201                # If we get connection reset by peer then try to RESUME
202                if isinstance(exc, OSError) and exc.errno in (54, 10054):
203                    ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id)
204                    continue
205
206                # We should only get this when an unhandled close code happens,
207                # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)
208                # sometimes, discord sends us 1000 for unknown reasons so we should reconnect
209                # regardless and rely on is_closed instead
210                if isinstance(exc, discord.ConnectionClosed):
211                    if exc.code == 4014:
212                        raise discord.PrivilegedIntentsRequired(exc.shard_id) from None
213                    if exc.code != 1000:
214                        await self.close()
215                        raise
216
217                retry = backoff.delay()
218                _log.exception("Attempting a reconnect in %.2fs", retry)
219                await asyncio.sleep(retry)
220                # Always try to RESUME the connection
221                # If the connection is not RESUME-able then the gateway will invalidate the session.
222                # This is apparently what the official Discord client does.
223                ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id)
224
225
226bot = MyBot(command_prefix="?")
227
228
229@bot.event
230async def on_ready():
231    print(f"Sucessfully logged in as {bot.user}")
232
233bot.run("YOUR_BOT_TOKEN")
234

Personally, I think that the following approach, which does include some runtime monkey-patching (but no AST manipulation) is cleaner for this purpose:

1def get_mobile():
2    """
3    The Gateway's IDENTIFY packet contains a properties field, containing $os, $browser and $device fields.
4    Discord uses that information to know when your phone client and only your phone client has connected to Discord,
5    from there they send the extended presence object.
6    The exact field that is checked is the $browser field. If it's set to Discord Android on desktop,
7    the mobile indicator is is triggered by the desktop client. If it's set to Discord Client on mobile,
8    the mobile indicator is not triggered by the mobile client.
9    The specific values for the $os, $browser, and $device fields are can change from time to time.
10    """
11    import ast
12    import inspect
13    import re
14    import discord
15
16    def source(o):
17        s = inspect.getsource(o).split("\n")
18        indent = len(s[0]) - len(s[0].lstrip())
19
20        return "\n".join(i[indent:] for i in s)
21
22    source_ = source(discord.gateway.DiscordWebSocket.identify)
23    patched = re.sub(
24        r'([\'"]\$browser[\'"]:\s?[\'"]).+([\'"])',
25        r"\1Discord Android\2",
26        source_,
27    )
28
29    loc = {}
30    exec(compile(ast.parse(patched), "<string>", "exec"), discord.gateway.__dict__, loc)
31    return loc["identify"]
32import discord
33import os
34from discord.ext import commands
35import mobile_status
36
37discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
38bot = commands.Bot(command_prefix="?")
39
40@bot.event
41async def on_ready():
42    print(f"Sucessfully logged in as {bot.user}")
43
44bot.run(os.getenv("DISCORD_TOKEN"))
45    async def identify(self):
46        """Sends the IDENTIFY packet."""
47        payload = {
48            'op': self.IDENTIFY,
49            'd': {
50                'token': self.token,
51                'properties': {
52                    '$os': sys.platform,
53                    '$browser': 'Discord Android',
54                    '$device': 'Discord Android',
55                    '$referrer': '',
56                    '$referring_domain': ''
57                },
58                'compress': True,
59                'large_threshold': 250,
60                'v': 3
61            }
62        }
63     # ...
64Traceback (most recent call last):
65  File "c:\Users\Achxy\Desktop\fresh\file.py", line 8, in <module>
66    print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
67  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1024, in getsource
68    lines, lnum = getsourcelines(object)
69  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 1006, in getsourcelines
70    lines, lnum = findsource(object)
71  File "C:\Users\Achxy\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 835, in findsource
72    raise OSError('could not get source code')
73OSError: could not get source code
74import discord
75import os
76from discord.ext import commands
77import mobile_status
78import inspect
79
80discord.gateway.DiscordWebSocket.identify = mobile_status.get_mobile()
81print(inspect.getsource(discord.gateway.DiscordWebSocket.identify))
82bot = commands.Bot(command_prefix="?")
83
84@bot.event
85async def on_ready():
86    print(f"Sucessfully logged in as {bot.user}")
87
88bot.run(os.getenv("DISCORD_TOKEN"))
89import asyncio
90import sys
91
92import aiohttp
93
94import discord
95from discord.gateway import DiscordWebSocket, _log
96from discord.ext.commands import Bot
97
98
99class MyGateway(DiscordWebSocket):
100
101    async def identify(self):
102        payload = {
103            'op': self.IDENTIFY,
104            'd': {
105                'token': self.token,
106                'properties': {
107                    '$os': sys.platform,
108                    '$browser': 'Discord Android',
109                    '$device': 'Discord Android',
110                    '$referrer': '',
111                    '$referring_domain': ''
112                },
113                'compress': True,
114                'large_threshold': 250,
115                'v': 3
116            }
117        }
118
119        if self.shard_id is not None and self.shard_count is not None:
120            payload['d']['shard'] = [self.shard_id, self.shard_count]
121
122        state = self._connection
123        if state._activity is not None or state._status is not None:
124            payload['d']['presence'] = {
125                'status': state._status,
126                'game': state._activity,
127                'since': 0,
128                'afk': False
129            }
130
131        if state._intents is not None:
132            payload['d']['intents'] = state._intents.value
133
134        await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
135        await self.send_as_json(payload)
136        _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
137
138
139class MyBot(Bot):
140
141    async def connect(self, *, reconnect: bool = True) -> None:
142        """|coro|
143
144        Creates a websocket connection and lets the websocket listen
145        to messages from Discord. This is a loop that runs the entire
146        event system and miscellaneous aspects of the library. Control
147        is not resumed until the WebSocket connection is terminated.
148
149        Parameters
150        -----------
151        reconnect: :class:`bool`
152            If we should attempt reconnecting, either due to internet
153            failure or a specific failure on Discord's part. Certain
154            disconnects that lead to bad state will not be handled (such as
155            invalid sharding payloads or bad tokens).
156
157        Raises
158        -------
159        :exc:`.GatewayNotFound`
160            If the gateway to connect to Discord is not found. Usually if this
161            is thrown then there is a Discord API outage.
162        :exc:`.ConnectionClosed`
163            The websocket connection has been terminated.
164        """
165
166        backoff = discord.client.ExponentialBackoff()
167        ws_params = {
168            'initial': True,
169            'shard_id': self.shard_id,
170        }
171        while not self.is_closed():
172            try:
173                coro = MyGateway.from_client(self, **ws_params)
174                self.ws = await asyncio.wait_for(coro, timeout=60.0)
175                ws_params['initial'] = False
176                while True:
177                    await self.ws.poll_event()
178            except discord.client.ReconnectWebSocket as e:
179                _log.info('Got a request to %s the websocket.', e.op)
180                self.dispatch('disconnect')
181                ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id)
182                continue
183            except (OSError,
184                    discord.HTTPException,
185                    discord.GatewayNotFound,
186                    discord.ConnectionClosed,
187                    aiohttp.ClientError,
188                    asyncio.TimeoutError) as exc:
189
190                self.dispatch('disconnect')
191                if not reconnect:
192                    await self.close()
193                    if isinstance(exc, discord.ConnectionClosed) and exc.code == 1000:
194                        # clean close, don't re-raise this
195                        return
196                    raise
197
198                if self.is_closed():
199                    return
200
201                # If we get connection reset by peer then try to RESUME
202                if isinstance(exc, OSError) and exc.errno in (54, 10054):
203                    ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id)
204                    continue
205
206                # We should only get this when an unhandled close code happens,
207                # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)
208                # sometimes, discord sends us 1000 for unknown reasons so we should reconnect
209                # regardless and rely on is_closed instead
210                if isinstance(exc, discord.ConnectionClosed):
211                    if exc.code == 4014:
212                        raise discord.PrivilegedIntentsRequired(exc.shard_id) from None
213                    if exc.code != 1000:
214                        await self.close()
215                        raise
216
217                retry = backoff.delay()
218                _log.exception("Attempting a reconnect in %.2fs", retry)
219                await asyncio.sleep(retry)
220                # Always try to RESUME the connection
221                # If the connection is not RESUME-able then the gateway will invalidate the session.
222                # This is apparently what the official Discord client does.
223                ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id)
224
225
226bot = MyBot(command_prefix="?")
227
228
229@bot.event
230async def on_ready():
231    print(f"Sucessfully logged in as {bot.user}")
232
233bot.run("YOUR_BOT_TOKEN")
234import sys
235from discord.gateway import DiscordWebSocket, _log
236from discord.ext.commands import Bot
237
238
239async def identify(self):
240    payload = {
241        'op': self.IDENTIFY,
242        'd': {
243            'token': self.token,
244            'properties': {
245                '$os': sys.platform,
246                '$browser': 'Discord Android',
247                '$device': 'Discord Android',
248                '$referrer': '',
249                '$referring_domain': ''
250            },
251            'compress': True,
252            'large_threshold': 250,
253            'v': 3
254        }
255    }
256
257    if self.shard_id is not None and self.shard_count is not None:
258        payload['d']['shard'] = [self.shard_id, self.shard_count]
259
260    state = self._connection
261    if state._activity is not None or state._status is not None:
262        payload['d']['presence'] = {
263            'status': state._status,
264            'game': state._activity,
265            'since': 0,
266            'afk': False
267        }
268
269    if state._intents is not None:
270        payload['d']['intents'] = state._intents.value
271
272    await self.call_hooks('before_identify', self.shard_id, initial=self._initial_identify)
273    await self.send_as_json(payload)
274    _log.info('Shard ID %s has sent the IDENTIFY payload.', self.shard_id)
275
276
277DiscordWebSocket.identify = identify
278bot = Bot(command_prefix="?")
279
280
281@bot.event
282async def on_ready():
283    print(f"Sucessfully logged in as {bot.user}")
284
285bot.run("YOUR_DISCORD_TOKEN")
286

As to why editing the library source code did not work for you, I can only assume that you have edited the wrong copy of the file, as people have commented.

Source https://stackoverflow.com/questions/70903401

QUESTION

Data path "" must NOT have additional properties(extractCss) in Angular 13 while upgrading project

Asked 2022-Jan-27 at 14:41

I am facing an issue while upgrading my project from angular 8.2.1 to angular 13 version.

After a successful upgrade while preparing a build it is giving me the following error.

1Data path "" must NOT have additional properties(extractCss).
2

I already renamed styleext with style in the angular.json file, but still not able to find the root cause for this error.

angular.json file is as follows.

1Data path "" must NOT have additional properties(extractCss).
2  {
3  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
4  "version": 1,
5  "newProjectRoot": "projects",
6  "projects": {
7    "qiwkCollaborator": {
8      "projectType": "application",
9      "schematics": {
10        "@schematics/angular:component": {
11          "style": "scss"
12        }
13      },
14      "root": "",
15      "sourceRoot": "src",
16      "prefix": "app",
17      "architect": {
18        "build": {
19
20        /*  "configurations": {
21            "fr": {
22            "aot": true,
23            "outputPath": "dist/qwikCollaborator/fr/",
24            "i18nFile": "src/translate/messages.fr.xlf",      
25            "i18nFormat": "xlf",      
26            "i18nLocale": "fr",      
27            "i18nMissingTranslation": "error"    
28             },
29             "en": {
30            "aot": true,
31            "outputPath": "dist/qwikCollaborator/en/",
32            "i18nFile": "src/translate/messages.en.xlf",      
33            "i18nFormat": "xlf",      
34            "i18nLocale": "en",      
35            "i18nMissingTranslation": "error"    
36             }  
37           },*/
38          "builder": "@angular-devkit/build-angular:browser",
39          "options": {
40            "outputPath": "dist/qiwkCollaborator",
41            "index": "src/index.html",
42            "main": "src/main.ts",
43            "polyfills": "src/polyfills.ts",
44            "tsConfig": "tsconfig.app.json",
45            "aot": false,
46            "assets": [
47              "src/favicon.ico",
48              "src/assets"
49            ],
50            "styles": [
51              "src/styles.scss",
52              "src/assets/css/custom-mobile.css",
53              "src/assets/css/custom.css"
54            ],
55            "scripts": [
56              "node_modules/jquery/dist/jquery.min.js",
57              "src/assets/js/qwikCollaborator.js"
58            ]
59          },
60          "configurations": {
61          "es5": {
62        "tsConfig": "./tsconfig.es5.json"
63      },
64            "production": {
65              "fileReplacements": [
66                {
67                  "replace": "src/environments/environment.ts",
68                  "with": "src/environments/environment.prod.ts"
69                }
70              ],
71              "optimization": true,
72              "outputHashing": "all",
73              "sourceMap": false,
74              "extractCss": true,
75              "namedChunks": false,
76              "aot": true,
77              "extractLicenses": true,
78              "vendorChunk": false,
79              "buildOptimizer": true,
80              "budgets": [
81                {
82                  "type": "initial",
83                  "maximumWarning": "2mb",
84                  "maximumError": "5mb"
85                },
86                {
87                  "type": "anyComponentStyle",
88                  "maximumWarning": "6kb",
89                  "maximumError": "10kb"
90                }
91              ]
92            }
93          }
94        },
95        "serve": {
96         /*  "configurations": {
97            "fr": {
98            "browserTarget": "qwikCollaborator:build:fr" 
99            },
100            "en": {
101            "browserTarget": "qwikCollaborator:build:en" 
102            } ,
103            },*/
104          "builder": "@angular-devkit/build-angular:dev-server",
105          "options": {
106            "browserTarget": "qiwkCollaborator:build"
107          },
108         
109          "configurations": {
110          "es5": {
111        "browserTarget": "qiwkCollaborator:build:es5"
112      },
113            "production": {
114              "browserTarget": "qiwkCollaborator:build:es5"
115            }
116          }
117        },
118        "extract-i18n": {
119          "builder": "@angular-devkit/build-angular:extract-i18n",
120          "options": {
121            "browserTarget": "qiwkCollaborator:build"
122          }
123        },
124        "test": {
125          "builder": "@angular-devkit/build-angular:karma",
126          "options": {
127            "main": "src/test.ts",
128            "polyfills": "src/polyfills.ts",
129            "tsConfig": "tsconfig.spec.json",
130            "karmaConfig": "karma.conf.js",
131            "assets": [
132              "src/favicon.ico",
133              "src/assets"
134            ],
135            "styles": [
136              "src/styles.scss"
137            ],
138            "scripts": ["../node_modules/jspdf/dist/jspdf.min.js"]
139          }
140        },
141        "lint": {
142          "builder": "@angular-devkit/build-angular:tslint",
143          "options": {
144            "tsConfig": [
145              "tsconfig.app.json",
146              "tsconfig.spec.json",
147              "e2e/tsconfig.json"
148            ],
149            "exclude": [
150              "**/node_modules/**"
151            ]
152          }
153        },
154        "e2e": {
155          "builder": "@angular-devkit/build-angular:protractor",
156          "options": {
157            "protractorConfig": "e2e/protractor.conf.js",
158            "devServerTarget": "qiwkCollaborator:serve"
159          },
160          "configurations": {
161            "production": {
162              "devServerTarget": "qiwkCollaborator:serve:production"
163            }
164          }
165        }
166      }
167    }},
168  "defaultProject": "qiwkCollaborator"
169}
170

How to get rid of this additional property?

can anyone help me with this?

thanks in advance!

ANSWER

Answered 2021-Dec-14 at 12:45

Just remove the "extractCss": true from your production environment, it will resolve the problem.

The reason about it is extractCss is deprecated, and it's value is true by default. See more here: Extracting CSS into JS with Angular 11 (deprecated extractCss)

Source https://stackoverflow.com/questions/70344098

QUESTION

Flutter Web: Cannot scroll with mouse down (drag) (Flutter 2.5+)

Asked 2022-Jan-19 at 09:57
[Update]

I can confirm this issue happened in flutter above 2.5. Using 2.2.3 is fine. The question becomes why this feature been removed in 2.5 ? And how to enable it in flutter 2.5?

[Origin Question]

I'm using SingleChildScrollView on flutter web with desktop browser. Scrolling only works on mouse wheel but not on mouse click (drag). How can I map mouse click to touch and scroll like mobile?

1import 'package:flutter/material.dart';
2
3void main() {
4  runApp(const MyApp());
5}
6
7class MyApp extends StatelessWidget {
8  const MyApp({Key? key}) : super(key: key);
9  @override
10  Widget build(BuildContext context) {
11    return MaterialApp(
12      title: 'Flutter Demo',
13      theme: ThemeData(
14        primarySwatch: Colors.blue,
15      ),
16      home: SingleChildScrollView(
17        child: Column(
18          children: List<Widget>.generate(50, (i) => Text(i.toString())).toList(),
19        ),
20      ),
21    );
22  }
23}
24
1import 'package:flutter/material.dart';
2
3void main() {
4  runApp(const MyApp());
5}
6
7class MyApp extends StatelessWidget {
8  const MyApp({Key? key}) : super(key: key);
9  @override
10  Widget build(BuildContext context) {
11    return MaterialApp(
12      title: 'Flutter Demo',
13      theme: ThemeData(
14        primarySwatch: Colors.blue,
15      ),
16      home: SingleChildScrollView(
17        child: Column(
18          children: List<Widget>.generate(50, (i) => Text(i.toString())).toList(),
19        ),
20      ),
21    );
22  }
23}
24flutter doctor -v
25[✓] Flutter (Channel master, 2.6.0-6.0.pre.6, on Ubuntu 20.04.3 LTS 5.11.0-34-generic, locale en_US.UTF-8)
26    • Flutter version 2.6.0-6.0.pre.6 at /home/XXX
27    • Upstream repository https://github.com/flutter/flutter.git
28    • Framework revision 0c5431d99c (12 days ago), 2021-09-05 22:31:02 -0400
29    • Engine revision b9c633900e
30    • Dart version 2.15.0 (build 2.15.0-82.0.dev)
31
32[✓] Chrome - develop for the web
33    • Chrome at google-chrome
34
35[✓] Connected device (2 available)
36    • Linux (desktop) • linux  • linux-x64      • Ubuntu 20.04.3 LTS 5.11.0-34-generic
37    • Chrome (web)    • chrome • web-javascript • Google Chrome 93.0.4577.82
38

ANSWER

Answered 2021-Sep-18 at 12:19

Flutter change mouse scroll behavior after 2.5. See this for detail.

1import 'package:flutter/material.dart';
2
3void main() {
4  runApp(const MyApp());
5}
6
7class MyApp extends StatelessWidget {
8  const MyApp({Key? key}) : super(key: key);
9  @override
10  Widget build(BuildContext context) {
11    return MaterialApp(
12      title: 'Flutter Demo',
13      theme: ThemeData(
14        primarySwatch: Colors.blue,
15      ),
16      home: SingleChildScrollView(
17        child: Column(
18          children: List<Widget>.generate(50, (i) => Text(i.toString())).toList(),
19        ),
20      ),
21    );
22  }
23}
24flutter doctor -v
25[✓] Flutter (Channel master, 2.6.0-6.0.pre.6, on Ubuntu 20.04.3 LTS 5.11.0-34-generic, locale en_US.UTF-8)
26    • Flutter version 2.6.0-6.0.pre.6 at /home/XXX
27    • Upstream repository https://github.com/flutter/flutter.git
28    • Framework revision 0c5431d99c (12 days ago), 2021-09-05 22:31:02 -0400
29    • Engine revision b9c633900e
30    • Dart version 2.15.0 (build 2.15.0-82.0.dev)
31
32[✓] Chrome - develop for the web
33    • Chrome at google-chrome
34
35[✓] Connected device (2 available)
36    • Linux (desktop) • linux  • linux-x64      • Ubuntu 20.04.3 LTS 5.11.0-34-generic
37    • Chrome (web)    • chrome • web-javascript • Google Chrome 93.0.4577.82
38class MyCustomScrollBehavior extends MaterialScrollBehavior {
39  // Override behavior methods and getters like dragDevices
40  @override
41  Set<PointerDeviceKind> get dragDevices => { 
42    PointerDeviceKind.touch,
43    PointerDeviceKind.mouse,
44    // etc.
45  };
46}
47
48// ScrollBehavior can be set for a specific widget.
49final ScrollController controller = ScrollController();
50ScrollConfiguration(
51  behavior: MyCustomScrollBehavior(),
52  child: ListView.builder(
53    controller: controller,
54    itemBuilder: (BuildContext context, int index) {
55     return Text('Item $index');
56    }
57  ),
58);
59

Source https://stackoverflow.com/questions/69232764

QUESTION

clarity.js by Microsoft slowing overall page loads

Asked 2022-Jan-17 at 16:40

I have a customer using bing tracking via https://bat.bing.com/bat.js.

On December, 6th 2021 it started calling in clarity.js without the customer making any changes to their code.

This slowed the overall page load by 1 second on mobile and 500ms on desktop. I've been trying to figure out how to disable this JS but I'm not sure what to do as it's being fired from the bing tracking js.

The bing tracking code is being triggered via google tag manager.

Anyone else having this issue and know how to disable clarity.js from being called at all?

enter image description here

Customer is using Wordpress. Amazing Bing can implement code that slows down a site overall page speed without any notification to the customer.

ANSWER

Answered 2021-Dec-17 at 18:16

We figured this out by going into our bing web tools and disabling the Clarity integration.

Source https://stackoverflow.com/questions/70281265

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Mobile

Tutorials and Learning Resources are not available at this moment for Mobile

Share this Page

share link

Get latest updates on Mobile