How to close a window in Shopware backend in my Plugin - plugins

I have a Plugin where I can create a shipping label. After i created it the window closes with win.destroy(); which is fine and i get back to the window that was open before. I would like to know
if i can close the window i get to after creating my label when i m doing the action? So I would like to close both windows that were open before.
here is the code
saveDpdconflist: function(orderid,win) {
var me = this;
dpdform = me.getDpdConf().getForm();
var dpdvalue = dpdform.getFieldValues();
dpdtabform = me.getDpdtabConf().getForm();
if (!dpdtabform.isValid()) {
Shopware.Notification.createGrowlMessage('',me.snippets.requireError,'');
return;
}
var dpdtabvalue = dpdtabform.getFieldValues();
var newstore = Ext.create('Shopware.apps.Order.DxOrderDpdtab.store.Dxorderlabel');
newstore.load({
params: {
dxorderid: orderid,
dxsalutation: dpdvalue.salutation,
dxfirstname: dpdvalue.firstName,
dxlastname: dpdvalue.lastName,
dxcompany: dpdvalue.company,
dxdepartment: '',
dxstreet: dpdvalue.street,
dxstreetno: dpdvalue.streetNumber,
dxcity: dpdvalue.city,
dxzipcode: dpdvalue.zipCode,
dxcountry: dpdvalue.countryname,
dxphone: dpdvalue.phone,
dxdpdproduct: dpdtabvalue.dxdpdshipname,
dxlabelpos: dpdtabvalue.labelposition_cmbx,
dxexportdoc: '1',
dxpayment: '1',
dxnoofgenpdf: dpdtabvalue.anzahlaversand,
dxcodtext: dpdtabvalue.nachnahmereferenz,
dxbyhand: '0',
dxweight: '5',
dxlblchgdpd: dpdvalue.dpdchngshipadd,
dxemail: dpdvalue.email,
dxshipdate: dpdtabvalue.from_date,
dxparcelshopid: win.record.raw.dxparcelshopid,
},
callback: function(data, operation) {
var records = operation.getRecords(),
record = records[0],
rawData = record.getProxy().getReader().rawData;
if(operation.success === true && rawData.data.error == '') {
if(rawData.data.number == '1'){
if(rawData.data.retoureOption == 1){
url = "{url controller='DxOrderDpdtab' action='getExportPDF'}";
url = url+'/id/'+(rawData.data.id-1);
window.open(url,'_blank');
}
url = "{url controller='DxOrderDpdtab' action='getExportPDF'}";
url = url+'/id/'+rawData.data.id;
window.open(url,'_blank');
}
Shopware.Notification.createGrowlMessage(me.snippets.successTitle,me.snippets.labelSuccessMessage,me.snippets.growlMessage);
win.destroy();
}
else{
Shopware.Notification.createGrowlMessage(me.snippets.failureTitle,rawData.data.error,me.snippets.growlMessage);
}
}
});
},

Related

Facebook photo upload date timestamp

I've downloaded all my Facebook data and wish to upload some of the images that I've sent via Messenger to Google Photos. I wish to have them to have the correct metadata so they are uploaded under the correct day, not under today. Unfortunately, they have the date of download for Date created.
I tried parsing the title, but it doesn't seem to be a timestamp.
My question is: is there a way to create a script that adds the correct metadata to a photo downloaded from Facebook (via Download your information archive)? An example title is: 142666616_209126620919024_535058535265435125_n.jpg. This photo should have the date Jan 27, 2021, 10:53 AM.
After some digging I found a solution.
The archive that Facebook gives you has folders for each friend with the following structure:
\friend_name_a1b2c3
\photos
12345678_123456788996_123124421.jpg
\gifs
\audio
messages_1.json
messages_1.json has all your messages with that friend and here is an example how a message looks like:
{
"sender_name": "Your Name",
"timestamp_ms": 1562647443588,
"photos": [
{
"uri": "messages/inbox/friend_name_a1b2c3/photos/12345678_123456788996_123124421.jpg",
"creation_timestamp": 1562647443
}
],
"type": "Generic",
"is_unsent": false
},
So, using glob and utimes I came up with the following script:
var glob = require("glob")
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require("fs"));
var { utimes } = require("utimes");
const readJSONFiles = async () => {
const messagesFiles = glob.sync(`**/message_*.json`)
const promises = [];
messagesFiles.forEach(mFile => {
promises.push(fs.readFileAsync(mFile, 'utf8'));
})
return Promise.all(promises);
}
readJSONFiles().then(result => {
const map = {};
result.forEach(data => {
const messagesContents = JSON.parse(data);
messagesContents.messages
.filter(m => m.photos)
.forEach(m => {
m.photos.filter(p => {
const splitted = p.uri.split("/")
const messagePhotoFileName = splitted[splitted.length - 1];
map[messagePhotoFileName] = m.timestamp_ms;
})
})
})
fs.writeFileSync("./map.json", JSON.stringify(map))
}).then(() => {
fs.readFileAsync("./map.json", 'utf8').then(data => {
const map = JSON.parse(data);
glob("**/*.jpg", function (er, files) {
files.forEach(file => {
const [, , photo] = file.split("/");
utimes(file, {
btime: map[photo],
atime: map[photo],
mtime: map[photo]
});
})
})
})
});
It creates a map of file-name:date-taken then loops over all .jpg files and changes its metadata. It definitely is a little rough around the edges but gets the job done, after all.

Why is CKEditor refusing my custom tag?

With a custom CKEditor plugin I am trying to insert a custom HTML tag, but the tag gets removed as soon as it is inserted into the editor. My plugin.js file:
CKEDITOR.plugins.add( 'tweet', {
icons: 'tweet',
init: function( editor ) {
editor.addCommand( 'insertTweet', {
allowedContent: 'tweet[:id]',
requiredContent: 'tweet',
exec: function( editor ) {
console.log('inserting');
editor.insertHtml( '<tweet :id="\'123\'" />' ); // also tried <tweet />
// editor.insertHtml( '[tweet :id="\'123\'" /]' ); // this works
}
});
editor.ui.addButton( 'tweet', {
label: 'Insert tweet',
command: 'insertTweet',
toolbar: 'insert,0'
});
}
});
The way I am adding the plugin for Bolt CMS backend:
function run() {
var extrasAdded = false;
if (typeof(CKEDITOR) == 'undefined') return;
CKEDITOR.plugins.addExternal('tweet', '/assets/plugins/tweet/plugin.js', '');
CKEDITOR.on('instanceReady', function (event, instance) {
if (extrasAdded === true) return;
var config = event.editor.config;
config.toolbar.push(
{ name: 'insert', items: [ 'tweet' ] }
);
config.extraPlugins += (config.extraPlugins ? ',' : '') + 'tweet';
config.extraAllowedContent = 'tweet'; // also tried 'tweet[:id]'
CKEDITOR.instances['body'].destroy();
CKEDITOR.replace('body', config);
extrasAdded = true;
});
}
if (document.readyState!='loading') run();
else document.addEventListener('DOMContentLoaded', run);
Can someone smart see why my tag is rejected?
So it turns out that we don't need the allowedContent or requiredContent properties in the plugin.js script. What did the trick was to tweak the editor's HTML DTD rules. In my case I got a reference to the editor in the instanceReady callback and tweeked it like this:
// name = 'tweet'
editor.filter.allow(name + "[!*]", name, true);
CKEDITOR.dtd[name] = CKEDITOR.dtd;
CKEDITOR.dtd.$empty[name] = 1; // allow self-closing tag
CKEDITOR.dtd.$blockLimit[name] = 1;
CKEDITOR.dtd.$nonEditable[name] = 1;
CKEDITOR.dtd.$object[name] = 1;
CKEDITOR.dtd.$inline[name] = 1; // $block won't work!
You can also see a full gist of it.

branch.io deeplink not working as expected in ionic 3

I have integrated branch.io deeplink in my ionic 3 application. I have successfully generated the link and the link opens up the app. But, I wanted to open a particular page instead of the homepage of the app.
So, I integrated the below code to the desired page:
dl(){
// only on devices
if (!this.platform.is('cordova')) { return }
const Branch = window['Branch'];
//only canonicalIdentifier is required
let properties = {
canonicalIdentifier: 'content/123',
canonicalUrl: 'https://example.com/content/123',
title: 'Content 123 Title',
contentDescription: 'Content 123 Description ' + Date.now(),
price: 12.12,
currency: 'GBD',
contentIndexingMode: 'private',
contentMetadata: {
custom: 'data',
testing: 123,
this_is: true
}
}
//create a branchUniversalObj variable to reference with other Branch methods
let branchUniversalObj = null
Branch.createBranchUniversalObject(properties).then(function (res) {
branchUniversalObj = res
//alert(JSON.stringify(res));
// optional fields
}).catch(function (err) {
alert('Error: ' + JSON.stringify(err))
})
let message = 'Check out this link'
Branch.initSession(function(data) {
if (data['+clicked_branch_link']) {
// read deep link data on click
alert('Deep Link Data: ' + JSON.stringify(data))
}
}).then(function(res) {
// create deep link
var analytics = {
channel: Date.now()
}
var properties = {}
branchUniversalObj.generateShortUrl(analytics, properties).then(function (res) {
alert('Response: ' + JSON.stringify(res.url))
}).catch(function (err) {
alert('Error: ' + JSON.stringify(err))
})
branchUniversalObj.onLinkShareResponse(function (res) {
alert('Goosebumps:' + JSON.stringify(res))
})
});
}
And I added the function to a button click. But, still it opens up the app home page when I click the created link.
It doesn't looks like you are using the correct setup for your deep link routing. Please reference this Branch documentation for best results: https://docs.branch.io/pages/deep-linking/routing/

Log in to Facebook with phantomjs - 302 issues?

I'm trying to write a phantomjs script to log in to my facebook account and take a screenshot.
Here's my code:
var page = require('webpage').create();
var system = require('system');
var stepIndex = 0;
var loadInProgress = false;
email = system.args[1];
password = system.args[2];
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
page.open("http://www.facebook.com/login.php", function(status) {
page.evaluate(function(email, password) {
document.querySelector("input[name='email']").value = email;
document.querySelector("input[name='pass']").value = password;
document.querySelector("#login_form").submit();
console.log("Login submitted!");
}, email, password);
page.render('output.png');
});
},
function() {
console.log(document.documentElement.innerHTML);
},
function() {
phantom.exit();
}
]
setInterval(function() {
if (!loadInProgress && typeof steps[stepIndex] == "function") {
console.log("step " + (stepIndex + 1));
steps[stepIndex]();
stepIndex++;
}
if (typeof steps[stepIndex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 10000);
(Inspired by this answer, but note that I've upped the interval to 10s)
Called like so:
./phantomjs test.js <email> <password>
With output (filtering out the selfxss warnings from Facebook):
step 1
load started
load finished
Login submitted!
load started
load finished
step 2
<head></head><body></body>
step 3
test
complete!
(Note that the html output in step two is empty)
This answer suggests that there are problems with phantomjs' SSL options, but running with --ssl-protocol=any has no effect.
This appears to be a similar problem, but for caspar, not phantomjs (and on Windows, not Mac) - I've tried using --ignore-ssl-errors=yes, but that also had no effect.
I guessed that this might be a redirection problem (and, indeed, when I replicate this on Chrome, the response from clicking "Submit" was a 302 Found with location https://www.facebook.com/checkpoint/?next), but according to this documentation I can set a page.onNavigationRequested handler - when I do so in my script, it doesn't get called.
I think this issue is related, but it looks as if there's no fix there.

where to put facebook ajax sign in file

i'm currently trying to migrate my site to yii. (still new to it too) in my site i have a facebook login code that looks like this
function updateButton(response) {
var b = document.getElementById("{$this->fbLoginButtonId}");
b.onclick = function(){
$("#{$this->fbLoginButtonId}").button("loading");
FB.login(function(response) {
if(response.authResponse) {
$('#processing').modal({show: true, backdrop: 'static', keyboard: false});
FB.api('/me', function(user) {
$.ajax({ type : 'post'
, url: '{$this->facebookLoginUrl}'
, data: ({ user: user })
, dataType: 'json'
, success: function(data){
if(data.error == 0){
window.location.href = data.success;
} else {
$('#processing').modal('hide');
showError(data.error);
$("#{$this->fbLoginButtonId}").button("reset");
}
}
});
});
} else { $("#{$this->fbLoginButtonId}").button("reset"); }
}, {scope: '{$this->facebookPermissions}'});
}
}
the line url: '{$this->facebookLoginUrl}' basically points to the file that does the authentication. in Yii, i put that file in protected/controllers/facebookcontroller.php
class FacebookController extends Controller {
public $defaultAction = 'facebook';
public function actionFacebook() {
if (app()->request->isAjaxRequest) {
$user = app()->request->getParam('user');
Shared::debug($user);
// verify one last time that facebook knows this guy
if($user['id'] === app()->facebook->getUser()){
$model = User::model()->findByEmail($user['email']);
if(!empty($model)){
// facebook email matches one in the user database
$identity = new UserIdentity( $model->email , null );
$identity->_ssoAuth = true;
$identity->authenticate();
if($identity->errorCode === UserIdentity::ERROR_NONE){
app()->user->login($identity, null);
echo json_encode(array('error' => false, 'success' => url('/')));
app()->end();
} else {
echo json_encode(array('error' => 'System Authentication Failed', 'code' => 'auth'));
app()->end();
}
} else {
// nothing found, this person should register
// write query to input into database!!!
}
} else {
// fb user id past from ajax does not match who facebook says they are...
echo json_encode(array('error' => 'Facebook Authentication Failed', 'code' => 'fb_auth'));
app()->end();
}
} else {
throw new CHttpException(403);
}
}
}
basically what do i put here url: '{$this->facebookLoginUrl}' ?? i tried http://localhost/facebook.html but doesn't work. i get this error on firebug
<h1>PHP Error [8]</h1>
<p>Undefined index: email (/Applications/XAMPP/xamppfiles/htdocs/protected/controllers/FacebookController.php:13)</p>
<pre>#0 /Applications/XAMPP/xamppfiles/htdocs/protected/controllers/FacebookController.php(13): CWebApplication->handleError()
#1 /Applications/XAMPP/xamppfiles/htdocs/yii/web/actions/CInlineAction.php(49): FacebookController->actionFacebook()
#2 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CController.php(308): CInlineAction->runWithParams()
#3 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CController.php(286): FacebookController->runAction()
#4 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CController.php(265): FacebookController->runActionWithFilters()
#5 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CWebApplication.php(282): FacebookController->run()
#6 /Applications/XAMPP/xamppfiles/htdocs/yii/web/CWebApplication.php(141): CWebApplication->runController()
#7 /Applications/XAMPP/xamppfiles/htdocs/yii/base/CApplication.php(180): CWebApplication->processRequest()
#8 /Applications/XAMPP/xamppfiles/htdocs/index.php(25): CWebApplication->run()
</pre>
the ajax post response looks like this..
user[birthday] MM/DD/YYYY
user[first_name] name
user[gender] male
user[hometown][id] 106031246101856
user[hometown][name] CITY, STATE
user[id] 598482999
user[last_name] LASTNAME
user[link] https://www.facebook.com/ID
user[locale] en_US
user[location][id] 106031246101856
user[location][name] CITY, STATE
user[middle_name] MIDDLENAME
user[name] FULLNAME
user[timezone] -8
user[updated_time] 2013-12-15T16:43:03+0000
user[username] USERNAME
user[verified] true
Yii generates url as http://www.example.com/index.php?r={controller_id}/{action_id}.
So in your case url will be http://www.example.com/index.php?r=facebook/facebook.
Learn how yii manges url's here.