Skip to content

Commit

Permalink
Merge branch 'Stay-2.1.x'
Browse files Browse the repository at this point in the history
  • Loading branch information
shenruisi committed Jun 1, 2022
2 parents d0f578b + 3c672cb commit 6e51948
Show file tree
Hide file tree
Showing 112 changed files with 6,124 additions and 1,249 deletions.
6 changes: 6 additions & 0 deletions Podfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#use_frameworks!
source 'https://github.com/CocoaPods/Specs.git'
target 'Stay' do
pod 'InterAppCommunication'
pod 'SDWebImage'
end
18 changes: 18 additions & 0 deletions Stay Extension/MatchPattern.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//
// MatchPattern.h
// Stay Extension
//
// Created by ris on 2022/5/25.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface MatchPattern : NSObject

- (instancetype)initWithPattern:(NSString *)pattern;
- (BOOL)doMatch:(NSString *)urlString;
@end

NS_ASSUME_NONNULL_END
153 changes: 153 additions & 0 deletions Stay Extension/MatchPattern.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
//
// MatchPattern.m
// Stay Extension
//
// Created by ris on 2022/5/25.
//

#import "MatchPattern.h"

@interface MatchPattern()

@property (nonatomic, assign) BOOL all;
@property (nonatomic, strong) NSString *protocol;
@property (nonatomic, assign) BOOL pass;
@property (nonatomic, strong) NSRegularExpression *hostExpr;
@property (nonatomic, strong) NSRegularExpression *pathExpr;

//Const members.
@property (nonatomic, strong) NSArray<NSString *> *validProtocols;
@property (nonatomic, strong) NSRegularExpression *REG_PARTS;
@property (nonatomic, strong) NSRegularExpression *REG_HOST;
@property (nonatomic, strong) NSRegularExpression *tldRegExp;

@end

@implementation MatchPattern

- (instancetype)initWithPattern:(NSString *)pattern{
if (self = [super init]){
if ([pattern isEqualToString:@"<all_urls>"]){
self.all = YES;
self.protocol = @"all_urls";
}

do{
NSArray<NSTextCheckingResult *> *results = [self.REG_PARTS matchesInString:pattern
options:0
range:NSMakeRange(0, pattern.length)];

if (results.count == 0){
NSLog(@"Pattern (%@) is not vailed",pattern);
break;
}

NSTextCheckingResult *result = results.firstObject;
NSInteger n = result.numberOfRanges;

if (n < 4){
NSLog(@"Pattern (%@) is not vailed",pattern);
break;
}

self.protocol = [pattern substringWithRange:[result rangeAtIndex:1]];
NSString *host = [pattern substringWithRange:[result rangeAtIndex:2]];
NSString *path = [pattern substringWithRange:[result rangeAtIndex:3]];

if (![self.protocol isEqualToString:@"*:"] && ![self.validProtocols containsObject:self.protocol]){
NSLog(@"@match: Invalid protocol (%@) specified.",self.protocol);
break;
}

results = [self.REG_HOST matchesInString:host options:0 range:NSMakeRange(0, host.length)];
if (results.count == 0){
NSLog(@"@match: Invalid host (%@) specified.",host);
break;
}

if (![[path substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"/"]){
NSLog(@"@match: Invalid path (%@) specified.",path);
break;
}

if (host.length > 0){
NSString *expr = [[[host stringByReplacingOccurrencesOfString:@"." withString:@"\\."]
stringByReplacingOccurrencesOfString:@"*" withString:@".*"]
stringByReplacingOccurrencesOfString:@"*." withString:@"*\\."];
self.hostExpr = [[NSRegularExpression alloc] initWithPattern:[NSString stringWithFormat:@"^%@$",expr] options:0 error:nil];

}

//TLD missed.
NSMutableString *builder = [[NSMutableString alloc] initWithString:@"^"];
for (int i = 0; i < path.length; i++){
unichar c = [path characterAtIndex:i];
switch(c){
case '*' : [builder appendString:@".*"];
break;
case '.' :
case '?' :
case '^' :
case '$' :
case '+' :
case '{' :
case '}' :
case '[' :
case ']' :
case '|' :
case '(' :
case ')' :
case '\\' : [builder appendFormat:@"\\%C",c];
break;
case ' ' :
break;
default : [builder appendFormat:@"%C",c];
break;
}
}

[builder appendString:@"$"];
self.pathExpr = [[NSRegularExpression alloc] initWithPattern:builder options:0 error:nil];
self.pass = YES;

}while(0);
}

return self;
}

- (NSArray<NSString *> *)validProtocols{
return @[@"http:", @"https:"];
}

- (NSRegularExpression *)REG_PARTS{
if (nil == _REG_PARTS){
_REG_PARTS = [[NSRegularExpression alloc] initWithPattern:@"^([a-z*]+:|\\*:)\\/\\/([^\\/]+)?(\\/.*)$" options:0 error:nil];
}
return _REG_PARTS;
}

- (NSRegularExpression *)REG_HOST{
if (nil == _REG_HOST){
_REG_HOST = [[NSRegularExpression alloc] initWithPattern:@"^(?:\\*\\.)?[^*\\/]+$|^\\*$|^$" options:0 error:nil];
}
return _REG_HOST;
}

- (NSRegularExpression *)tldRegExp{
if (nil == _tldRegExp){
_tldRegExp = [[NSRegularExpression alloc] initWithPattern:@"^([^:]+:\\/\\/[^\\/]+)\\.tld(\\/.*)?$" options:0 error:nil];
}
return _tldRegExp;
}

- (BOOL)doMatch:(NSString *)urlString{
if(!self.pass) return NO;
NSURL *url = [NSURL URLWithString:urlString];
if (!url) return NO;
if (self.all) return YES;

return [self.hostExpr matchesInString:url.host options:0 range:NSMakeRange(0, url.host.length)].count > 0
&& [self.pathExpr matchesInString:url.path options:0 range:NSMakeRange(0, url.path.length)].count > 0;
}
@end
13 changes: 10 additions & 3 deletions Stay Extension/Resources/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
if ("bootstrap" == request.from || "iframe" == request.from) {
if ("fetchScripts" == request.operate) {
console.log("background---fetchScripts request==", request);
browser.runtime.sendNativeMessage("application.id", { type: request.operate }, function (response) {
browser.runtime.sendNativeMessage("application.id", { type: request.operate, url: request.url, digest: request.digest }, function (response) {
sendResponse(response);
});
return true;
Expand Down Expand Up @@ -449,7 +449,14 @@ browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
sendResponse(response);
});

} else if ("fetchMatchedScriptLog" == request.operate) {
}
else if ("exeScriptManually" == request.operate) {
browser.tabs.query({ active: true, currentWindow: true }, (tabs) => {
browser.tabs.sendMessage(tabs[0].id, { from: "background", operate: "exeScriptManually", uuid: request.uuid });
});

}
else if ("fetchMatchedScriptLog" == request.operate) {
if (matchAppScriptList && matchAppScriptList.length > 0) {
if (matchAppScriptConsole.length > 0) {
matchAppScriptConsole = [];
Expand Down Expand Up @@ -545,4 +552,4 @@ function xhrAddListeners(xhr, tab, id, xhrId, details) {
if (details.ontimeout) {
xhr.addEventListener("timeout", e => xhrHandleEvent(e, xhr, tab, id, xhrId));
}
}
}
107 changes: 87 additions & 20 deletions Stay Extension/Resources/bootstrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const $_matchesCheck = (userLibraryScript,url) => {
if (matched){
for (var i = 0; i < userLibraryScript.includes.length; i++){
matched = matchRule(url.href, userLibraryScript.includes[i]);
console.log("matchRule",url.href,userLibraryScript.includes[i],matched);
// console.log("matchRule",url.href,userLibraryScript.includes[i],matched);
if (matched) break;
}

Expand Down Expand Up @@ -100,7 +100,7 @@ const $_injectInPageWithTiming = (script, runAt) => {
} else {
$_injectInPage(script);
}
} else if (runAt === "document_end") {
} else if (runAt === "document_end" || runAt === "document_body") {
if (document.readyState !== "loading") {
$_injectInPage(script);
} else {
Expand All @@ -121,7 +121,7 @@ const $_injectInPageWithTiming = (script, runAt) => {
}
}

//let injectScripts = []
let matchedScripts;
(function(){
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
let operate = request.operate;
Expand All @@ -132,6 +132,69 @@ const $_injectInPageWithTiming = (script, runAt) => {
let menuId = request.id;
window.postMessage({ name: "execRegisterMenuCommand", menuId: menuId, id: id });
}
else if (request.from == "background" && "exeScriptManually" === operate){
let targetScript;
for (var i=0; i < matchedScripts.length; i++){
if (matchedScripts[i].uuid == request.uuid){
targetScript = matchedScripts[i];
break;
}
}

if (targetScript){
if (targetScript.requireUrls.length > 0){
targetScript.requireUrls.forEach((url)=>{
if (injectedVendor.has(url)) return;
injectedVendor.add(url);
if (url.startsWith('stay://')){
browser.runtime.sendMessage({
from: "bootstrap",
operate: "injectFile",
file:$_res($_uri(url).pathname.substring(1)),
allFrames:true,
runAt:"document_start"
});
}
else{
var pageInject = script.installType === "page";
console.log("pageInject---",pageInject)
targetScript.requireCodes.forEach((urlCodeDic)=>{
if (urlCodeDic.url == url){
if (pageInject){
$_injectRequiredInPage(urlCodeDic.name,urlCodeDic.code);
}
else{
browser.runtime.sendMessage({
from: "bootstrap",
operate: "injectScript",
code:urlCodeDic.code,
allFrames:true,
runAt:"document_start"
});
}

}
});
}
});
}

if (targetScript.installType === "page"){
console.log("Manually page inject");
$_injectInPageWithTiming(targetScript,"document_start");
}
else{
console.log("Manually content inject");
browser.runtime.sendMessage({
from: "bootstrap",
operate: "injectScript",
code:targetScript.content,
allFrames:!targetScript.noFrames,
runAt:"document_start"
});
}
}
}
else if (operate.startsWith("RESP_API_XHR_BG_")) {
// only respond to messages on the correct content script
if (request.id !== id) return;
Expand Down Expand Up @@ -161,19 +224,29 @@ const $_injectInPageWithTiming = (script, runAt) => {
}
return true;
});
browser.runtime.sendMessage({ from: "bootstrap", operate: "fetchScripts" }, (response) => {

browser.runtime.sendMessage({ from: "bootstrap", operate: "fetchScripts", url: location.href, digest: "no"}, (response) => {
let injectedVendor = new Set();
let userLibraryScripts = JSON.parse(response.body);
let injectScripts = [];
userLibraryScripts.forEach((userLibraryScript)=>{
console.log(userLibraryScript);

if ($_matchesCheck(userLibraryScript,new URL(location.href))){
injectScripts.push(userLibraryScript);
}
});
// let userLibraryScripts = response.body; //JSON.parse(response.body);
// console.log("response",response.body);
// let injectScripts = [];
// userLibraryScripts.forEach((userLibraryScript)=>{
// console.log("script from library",userLibraryScript);
// try {
// if ($_matchesCheck(userLibraryScript,new URL(location.href))){
// console.log("userLibraryScript-", userLibraryScript)
// injectScripts.push(userLibraryScript);
// }
//
// } catch (error) {
// console.error("¥_matchesCheck-----error", error)
// }
// });

matchedScripts = response.body;

injectScripts.forEach((script) => {
console.log("matchedScripts-", matchedScripts)
matchedScripts.forEach((script) => {
if (script.requireUrls.length > 0 && script.active){
script.requireUrls.forEach((url)=>{
if (injectedVendor.has(url)) return;
Expand Down Expand Up @@ -228,12 +301,6 @@ const $_injectInPageWithTiming = (script, runAt) => {

}
});

browser.runtime.sendMessage({
from: "bootstrap",
operate: "setMatchedScripts",
matchScripts: injectScripts
});
});
window.addEventListener('message', (e) => {
if (!e || !e.data || !e.data.name) return;
Expand Down
34 changes: 34 additions & 0 deletions Stay Extension/Resources/checkUserscript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@



console.log("test checkUserscript")
let userscriptText = document.body.textContent;

let meta = extractMeta(userscriptText).match(/.+/g);
const is_dark = () => {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}
if(meta){
let url = encodeURIComponent(window.location.href);
let stayImg = browser.runtime.getURL("images/icon-256.png");
let bg = "background: #fff;";
let fontColor = "color: #000000;"
if (is_dark()) {
bg = "background: #000;";
fontColor = "color: #F3F3F3;"
}
let schemeUrl = "stay://x-callback-url/install?scriptURL="+url;
let popToastTemp = [
'<div id="popToast" style="width: 270px;height: 57px;transform: translateX(-50%);border-radius: 16px; ' + bg + ' position: fixed; bottom: 10;left: 50%;box-shadow: 0 12px 32px rgba(0, 0, 0, .1), 0 2px 6px rgba(0, 0, 0, .08);display: flex;flex-direction: row;">',
'<a id="popImg" href="' + schemeUrl +'" style="text-decoration: none;width: 75px;display: flex;flex-direction: row;align-items:center;justify-content: center;justify-items: center;"><img src=' + stayImg +' style="width: 46px;height: 46px;"></img></a>',
'<a id="popInstall" href="' + schemeUrl +'" style="font-family:Helvetica Neue;text-decoration: none;display: flex;flex-direction: column;justify-content: center;justify-items: center;align-items:center;line-height:23px;">',
'<div style="font-size: 17px; color: #B620E0;font-weight:700;">Tap to install</div>',
'<div style="font-size: 13px; ' + fontColor +' ">Stay 2 - Local scrip manager</div>',
'</a>',
'</div>'
];
let temp = popToastTemp.join("");
let tempDom = document.createElement("div");
tempDom.innerHTML = temp;
document.body.appendChild(tempDom);
}
Binary file added Stay Extension/Resources/images/manaully.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 6e51948

Please sign in to comment.