CCMain.m 254 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import <OCCommunicationLib/OCActivity.h>
  29. #import <OCCommunicationLib/OCNotifications.h>
  30. #import <OCCommunicationLib/OCNotificationsAction.h>
  31. #import <OCCommunicationLib/OCFrameworkConstants.h>
  32. #import <OCCommunicationLib/OCCapabilities.h>
  33. #import "CTAssetCheckmark.h"
  34. #ifdef CUSTOM_BUILD
  35. #import "CustomSwift.h"
  36. #else
  37. #import "Nextcloud-Swift.h"
  38. #endif
  39. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  40. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  41. #define alertCreateFolder 1
  42. #define alertCreateFolderCrypto 2
  43. #define alertRename 3
  44. #define alertOfflineFolder 4
  45. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  46. {
  47. CCMetadata *_metadata;
  48. BOOL _isRoot;
  49. BOOL _isViewDidLoad;
  50. BOOL _isOfflineServerUrl;
  51. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  52. BOOL _isSelectedMode;
  53. NSMutableArray *_selectedMetadatas;
  54. NSMutableArray *_queueSelector;
  55. NSUInteger _numSelectedMetadatas;
  56. UIImageView *_ImageTitleHomeCryptoCloud;
  57. UIView *_reMenuBackgroundView;
  58. UITapGestureRecognizer *_singleFingerTap;
  59. NSString *_directoryGroupBy;
  60. NSString *_directoryOrder;
  61. NSUInteger _failedAttempts;
  62. NSDate *_lockUntilDate;
  63. NSString *_fatherPermission;
  64. UIRefreshControl *_refreshControl;
  65. UIDocumentInteractionController *_docController;
  66. CCHud *_hud;
  67. CCHud *_hudDeterminate;
  68. // Datasource
  69. CCSectionDataSourceMetadata *_sectionDataSource;
  70. NSDate *_dateReadDataSource;
  71. // Search
  72. BOOL _isSearchMode;
  73. NSString *_searchFileName;
  74. NSMutableArray *_searchResultMetadatas;
  75. NSString *_depth;
  76. NSString *_noFilesSearchTitle;
  77. NSString *_noFilesSearchDescription;
  78. // Login
  79. CCLoginWeb *_loginWeb;
  80. CCLogin *_loginVC;
  81. }
  82. @end
  83. @implementation CCMain
  84. #pragma --------------------------------------------------------------------------------------------
  85. #pragma mark ===== Init =====
  86. #pragma --------------------------------------------------------------------------------------------
  87. - (id)initWithCoder:(NSCoder *)aDecoder
  88. {
  89. if (self = [super initWithCoder:aDecoder]) {
  90. _directoryOrder = [CCUtility getOrderSettings];
  91. _directoryGroupBy = [CCUtility getGroupBySettings];
  92. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  93. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  94. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  95. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  96. }
  97. return self;
  98. }
  99. #pragma --------------------------------------------------------------------------------------------
  100. #pragma mark ===== View =====
  101. #pragma --------------------------------------------------------------------------------------------
  102. - (void)viewDidLoad
  103. {
  104. [super viewDidLoad];
  105. // init object
  106. _metadata = [CCMetadata new];
  107. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  108. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  109. _selectedMetadatas = [NSMutableArray new];
  110. _queueSelector = [NSMutableArray new];
  111. _isViewDidLoad = YES;
  112. _fatherPermission = @"";
  113. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  114. _searchResultMetadatas = [NSMutableArray new];
  115. _searchFileName = @"";
  116. _depth = @"0";
  117. _noFilesSearchTitle = @"";
  118. _noFilesSearchDescription = @"";
  119. // delegate
  120. self.tableView.delegate = self;
  121. self.tableView.tableFooterView = [UIView new];
  122. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  123. self.tableView.emptyDataSetDelegate = self;
  124. self.tableView.emptyDataSetSource = self;
  125. self.searchController.delegate = self;
  126. self.searchController.searchBar.delegate = self;
  127. [[CCNetworking sharedNetworking] settingDelegate:self];
  128. // Custom Cell
  129. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  130. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  131. // long press recognizer TableView
  132. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  133. [self.tableView addGestureRecognizer:longPressRecognizer];
  134. // Pull-to-Refresh
  135. [self createRefreshControl];
  136. // Register for 3D Touch Previewing if available
  137. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  138. {
  139. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  140. }
  141. // Back Button
  142. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  143. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogo] style:UIBarButtonItemStylePlain target:nil action:nil];
  144. // reMenu Background
  145. _reMenuBackgroundView = [[UIView alloc] init];
  146. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  147. // if this is not Main (the Main uses inizializeMain)
  148. if (_isRoot == NO && app.activeAccount.length > 0) {
  149. // Settings this folder & delegate & Loading datasource
  150. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  151. // Load Datasource
  152. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  153. // Read Folder
  154. [self readFolderWithForced:NO serverUrl:_serverUrl];
  155. }
  156. // Version Server
  157. app.serverVersion = [CCCoreData getServerVersionMajorActiveAccount:app.activeAccount];
  158. // Title
  159. [self setTitle];
  160. // Search
  161. self.definesPresentationContext = YES;
  162. self.searchController.searchResultsUpdater = self;
  163. self.searchController.dimsBackgroundDuringPresentation = NO;
  164. self.tableView.tableHeaderView = self.searchController.searchBar;
  165. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  166. [self.searchController.searchBar sizeToFit];
  167. self.searchController.searchBar.delegate = self;
  168. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  169. if (app.serverVersion >= 12) {
  170. if (_isRoot)
  171. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  172. else
  173. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  174. } else {
  175. self.searchController.searchBar.scopeButtonTitles = nil;
  176. }
  177. // Hide Search Filed on Load
  178. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  179. }
  180. // Apparirà
  181. - (void)viewWillAppear:(BOOL)animated
  182. {
  183. [super viewWillAppear:animated];
  184. // test
  185. if (app.activeAccount.length == 0)
  186. return;
  187. // Settings this folder & delegate & Loading datasource
  188. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  189. [[CCNetworking sharedNetworking] settingDelegate:self];
  190. // Color
  191. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  192. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  193. // Menu e Bar
  194. [self createReMainMenu];
  195. [self createReSelectMenu];
  196. if (_isSelectedMode)
  197. [self setUINavigationBarSelected];
  198. else
  199. [self setUINavigationBarDefault];
  200. // Plus Button
  201. [app plusButtonVisibile:true];
  202. }
  203. // E' arrivato
  204. - (void)viewDidAppear:(BOOL)animated
  205. {
  206. [super viewDidAppear:animated];
  207. // Active Main
  208. app.activeMain = self;
  209. // Test viewDidLoad
  210. if (_isViewDidLoad) {
  211. _isViewDidLoad = NO;
  212. } else {
  213. if (app.activeAccount.length > 0) {
  214. // Load Datasource
  215. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  216. // Read Folder
  217. [self readFolderWithForced:NO serverUrl:_serverUrl];
  218. }
  219. }
  220. // Title
  221. [self setTitle];
  222. }
  223. - (void)viewWillDisappear:(BOOL)animated
  224. {
  225. [super viewWillDisappear:animated];
  226. [self closeAllMenu];
  227. }
  228. - (void)didReceiveMemoryWarning
  229. {
  230. [super didReceiveMemoryWarning];
  231. // Dispose of any resources that can be recreated.
  232. }
  233. - (BOOL)prefersStatusBarHidden
  234. {
  235. return NO;
  236. }
  237. // detect scroll for remove keyboard in search mode
  238. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  239. {
  240. if (_isSearchMode && scrollView == self.tableView) {
  241. [self.searchController.searchBar endEditing:YES];
  242. }
  243. }
  244. #pragma --------------------------------------------------------------------------------------------
  245. #pragma mark ===== Initizlize Mail =====
  246. #pragma --------------------------------------------------------------------------------------------
  247. - (void)initializeMain:(NSNotification *)notification
  248. {
  249. _directoryGroupBy = nil;
  250. _directoryOrder = nil;
  251. _dateReadDataSource = nil;
  252. // test
  253. if (app.activeAccount.length == 0)
  254. return;
  255. if ([app.listMainVC count] == 0 || _isRoot) {
  256. // This is Root
  257. _isRoot = YES;
  258. // Crypto Mode
  259. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  260. app.isCryptoCloudMode = NO;
  261. } else {
  262. app.isCryptoCloudMode = YES;
  263. }
  264. // go Home
  265. [self.navigationController popToRootViewControllerAnimated:NO];
  266. // Remove search mode
  267. [self cancelSearchBar];
  268. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  269. _isFolderEncrypted = NO;
  270. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  271. // add list
  272. [app.listMainVC setObject:self forKey:_serverUrl];
  273. // setting Networking
  274. [[CCNetworking sharedNetworking] settingDelegate:self];
  275. [[CCNetworking sharedNetworking] settingAccount];
  276. // populate shared Link & User variable
  277. [CCCoreData populateSharesVariableFromDBActiveAccount:app.activeAccount sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup];
  278. // Load Datasource
  279. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  280. // Load Folder
  281. [self readFolderWithForced:NO serverUrl:_serverUrl];
  282. // Load photo datasorce
  283. if (app.activePhotosCameraUpload)
  284. [app.activePhotosCameraUpload reloadDatasourceForced];
  285. // remove all of detail
  286. if (app.activeDetail)
  287. [app.activeDetail removeAllView];
  288. // remove all Notification Messages
  289. [app.listOfNotifications removeAllObjects];
  290. // home main
  291. app.homeMain = self;
  292. // Initializations
  293. [app applicationInitialized];
  294. } else {
  295. // reload datasource
  296. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  297. }
  298. }
  299. #pragma --------------------------------------------------------------------------------------------
  300. #pragma mark ==== DZNEmptyDataSetSource ====
  301. #pragma --------------------------------------------------------------------------------------------
  302. /*
  303. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  304. {
  305. if(_isSearchMode)
  306. return NO;
  307. else
  308. return YES;
  309. }
  310. */
  311. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  312. {
  313. return YES;
  314. }
  315. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  316. {
  317. return [UIColor whiteColor];
  318. }
  319. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. if (_isSearchMode)
  322. return [UIImage imageNamed:image_searchBig];
  323. else
  324. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_filesNoFiles] color:[NCBrandColor sharedInstance].brand];
  325. }
  326. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  327. {
  328. NSString *text;
  329. if (_isSearchMode)
  330. text = _noFilesSearchTitle;
  331. else
  332. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  333. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  334. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  335. }
  336. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  337. {
  338. NSString *text;
  339. if (_isSearchMode)
  340. text = _noFilesSearchDescription;
  341. else
  342. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  343. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  344. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  345. paragraph.alignment = NSTextAlignmentCenter;
  346. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  347. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  348. }
  349. #pragma --------------------------------------------------------------------------------------------
  350. #pragma mark ===== AlertView =====
  351. #pragma --------------------------------------------------------------------------------------------
  352. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  353. {
  354. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  355. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  356. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  357. if (alertView.tag == alertRename && buttonIndex == 1) {
  358. if ([_metadata.model isEqualToString:@"note"]) {
  359. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  360. } else {
  361. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  362. }
  363. }
  364. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  365. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  366. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  367. [[CCSynchronize sharedSynchronize] addOfflineFolder:dir];
  368. [self performSelector:@selector(reloadDatasource) withObject:nil];
  369. }
  370. }
  371. // accept only number char > 0
  372. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  373. {
  374. /* Retrieve a text field at an index -
  375. raises NSRangeException when textFieldIndex is out-of-bounds.
  376. The field at index 0 will be the first text field
  377. (the single field or the login field),
  378. The field at index 1 will be the password field. */
  379. /*
  380. 1> Get the Text Field in alertview
  381. 2> Get the text of that Text Field
  382. 3> Verify that text length
  383. 4> return YES or NO Based on the length
  384. */
  385. if (alertView.tag == alertOfflineFolder) return YES;
  386. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  387. }
  388. #pragma --------------------------------------------------------------------------------------------
  389. #pragma mark ===== Graphic Window =====
  390. #pragma --------------------------------------------------------------------------------------------
  391. - (void)createRefreshControl
  392. {
  393. _refreshControl = [UIRefreshControl new];
  394. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  395. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  396. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  397. [self setRefreshControl:_refreshControl];
  398. }
  399. - (void)deleteRefreshControl
  400. {
  401. [_refreshControl endRefreshing];
  402. self.refreshControl = nil;
  403. }
  404. - (void)refreshControlTarget
  405. {
  406. [self readFolderWithForced:YES serverUrl:_serverUrl];
  407. // Actuate `Peek` feedback (weak boom)
  408. AudioServicesPlaySystemSound(1519);
  409. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  410. }
  411. - (void)setTitle
  412. {
  413. // Color text self.navigationItem.title
  414. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  415. if (_isSelectedMode) {
  416. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  417. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  418. self.navigationItem.titleView = nil;
  419. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  420. } else {
  421. // we are in home : LOGO BRAND
  422. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  423. self.navigationItem.title = nil;
  424. if ([app.reachability isReachable] == NO) _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogoOffline]];
  425. else _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogo]];
  426. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  427. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  428. [singleTap setNumberOfTapsRequired:1];
  429. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  430. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  431. } else {
  432. self.navigationItem.title = _titleMain;
  433. }
  434. }
  435. }
  436. - (void)setUINavigationBarDefault
  437. {
  438. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  439. UIBarButtonItem *buttonMore, *buttonNotification;
  440. // =
  441. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_navigationControllerMenu] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  442. buttonMore.enabled = true;
  443. // <
  444. self.navigationController.navigationBar.hidden = NO;
  445. // Notification
  446. if ([app.listOfNotifications count] > 0) {
  447. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_notification] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  448. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  449. buttonNotification.enabled = true;
  450. }
  451. if (buttonNotification)
  452. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  453. else
  454. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  455. self.navigationItem.leftBarButtonItem = nil;
  456. }
  457. - (void)setUINavigationBarSelected
  458. {
  459. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  460. UIImage *icon = [UIImage imageNamed:image_navigationControllerMenu];
  461. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  462. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  463. self.navigationItem.leftBarButtonItem = leftButton;
  464. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  465. }
  466. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  467. {
  468. [self closeAllMenu];
  469. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  470. }];
  471. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  472. }
  473. - (void)cancelSelect
  474. {
  475. [self tableViewSelect:NO];
  476. }
  477. - (void)closeAllMenu
  478. {
  479. // close Menu
  480. [app.reSelectMenu close];
  481. [app.reMainMenu close];
  482. // Close Menu Logo
  483. [CCMenuAccount dismissMenu];
  484. }
  485. #pragma --------------------------------------------------------------------------------------------
  486. #pragma mark ===== Document Picker =====
  487. #pragma --------------------------------------------------------------------------------------------
  488. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  489. {
  490. NSLog(@"Cancelled");
  491. }
  492. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  493. {
  494. NSLog(@"Cancelled");
  495. }
  496. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  497. {
  498. documentPicker.delegate = self;
  499. [self presentViewController:documentPicker animated:YES completion:nil];
  500. }
  501. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  502. {
  503. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  504. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  505. __block NSError *error;
  506. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  507. NSString *fileName = [url lastPathComponent];
  508. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  509. NSData *data = [NSData dataWithContentsOfURL:newURL];
  510. if (data && error == nil) {
  511. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  512. // Upload File
  513. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  514. } else {
  515. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  516. }
  517. } else {
  518. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  519. }
  520. }];
  521. }
  522. }
  523. - (void)openImportDocumentPicker
  524. {
  525. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  526. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  527. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  528. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  529. documentProviderMenu.delegate = self;
  530. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  531. }
  532. #pragma --------------------------------------------------------------------------------------------
  533. #pragma mark ===== Assets Picker =====
  534. #pragma --------------------------------------------------------------------------------------------
  535. - (void)openAssetsPickerController
  536. {
  537. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  538. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  539. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  540. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  541. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  542. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  543. dispatch_async(dispatch_get_main_queue(), ^{
  544. // init picker
  545. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  546. // set delegate
  547. picker.delegate = self;
  548. // to show selection order
  549. //picker.showsSelectionIndex = YES;
  550. // to present picker as a form sheet in iPad
  551. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  552. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  553. // present picker
  554. [self presentViewController:picker animated:YES completion:nil];
  555. });
  556. }];
  557. }
  558. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  559. {
  560. [picker dismissViewControllerAnimated:YES completion:^{
  561. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  562. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  563. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  564. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  565. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  566. [self presentViewController:navigationController animated:YES completion:nil];
  567. }];
  568. }
  569. #pragma --------------------------------------------------------------------------------------------
  570. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  571. #pragma --------------------------------------------------------------------------------------------
  572. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  573. {
  574. // evitiamo il rimando della eventuale photo e/o video
  575. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  576. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  577. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  578. }
  579. }
  580. #pragma --------------------------------------------------------------------------------------------
  581. #pragma mark ===== UnZipFile =====
  582. #pragma --------------------------------------------------------------------------------------------
  583. - (void)unZipFile:(NSString *)fileID
  584. {
  585. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  586. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  587. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  588. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  589. dispatch_async(dispatch_get_main_queue(), ^{
  590. float progress = (float) entryNumber / (float)total;
  591. [_hudDeterminate progress:progress];
  592. });
  593. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  594. dispatch_async(dispatch_get_main_queue(), ^{
  595. [_hudDeterminate hideHud];
  596. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  597. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  598. });
  599. }];
  600. });
  601. }
  602. #pragma --------------------------------------------------------------------------------------------
  603. #pragma mark ===== Create New (OpenModel) =====
  604. #pragma --------------------------------------------------------------------------------------------
  605. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  606. {
  607. UIViewController *viewController;
  608. NSString *fileName, *uuid, *fileID, *serverUrl;
  609. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  610. [self.tableView deselectRowAtIndexPath:index animated:NO];
  611. if (isnew) {
  612. fileName = nil;
  613. uuid = [CCUtility getUUID];
  614. fileID = nil;
  615. serverUrl = _serverUrl;
  616. } else {
  617. fileName = _metadata.fileName;
  618. uuid = _metadata.uuid;
  619. fileID = _metadata.fileID;
  620. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  621. }
  622. if ([tipo isEqualToString:@"cartadicredito"])
  623. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  624. if ([tipo isEqualToString:@"bancomat"])
  625. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  626. if ([tipo isEqualToString:@"contocorrente"])
  627. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  628. if ([tipo isEqualToString:@"accountweb"])
  629. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  630. if ([tipo isEqualToString:@"patenteguida"])
  631. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  632. if ([tipo isEqualToString:@"cartaidentita"])
  633. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  634. if ([tipo isEqualToString:@"passaporto"])
  635. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  636. if ([tipo isEqualToString:@"note"]) {
  637. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  638. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  639. [self presentViewController:navigationController animated:YES completion:nil];
  640. } else {
  641. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  642. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  643. [self presentViewController:navigationController animated:YES completion:nil];
  644. }
  645. }
  646. // New folder or new photo or video
  647. - (void)returnCreate:(NSInteger)type
  648. {
  649. switch (type) {
  650. /* PLAIN */
  651. case k_returnCreateFolderPlain: {
  652. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  653. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  654. alertView.tag = alertCreateFolder;
  655. [alertView show];
  656. }
  657. break;
  658. case k_returnCreateFotoVideoPlain: {
  659. _isPickerCriptate = false;
  660. [self openAssetsPickerController];
  661. }
  662. break;
  663. case k_returnCreateFilePlain: {
  664. _isPickerCriptate = false;
  665. [self openImportDocumentPicker];
  666. }
  667. break;
  668. /* ENCRYPTED */
  669. case k_returnCreateFolderEncrypted: {
  670. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  671. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  672. alertView.tag = alertCreateFolderCrypto;
  673. [alertView show];
  674. }
  675. break;
  676. case k_returnCreateFotoVideoEncrypted: {
  677. _isPickerCriptate = true;
  678. [self openAssetsPickerController];
  679. }
  680. break;
  681. case k_returnCreateFileEncrypted: {
  682. _isPickerCriptate = true;
  683. [self openImportDocumentPicker];
  684. }
  685. break;
  686. /* UTILITY */
  687. case k_returnNote:
  688. [self openModel:@"note" isNew:true];
  689. break;
  690. case k_returnAccountWeb:
  691. [self openModel:@"accountweb" isNew:true];
  692. break;
  693. /* BANK */
  694. case k_returnCartaDiCredito:
  695. [self openModel:@"cartadicredito" isNew:true];
  696. break;
  697. case k_returnBancomat:
  698. [self openModel:@"bancomat" isNew:true];
  699. break;
  700. case k_returnContoCorrente:
  701. [self openModel:@"contocorrente" isNew:true];
  702. break;
  703. /* DOCUMENT */
  704. case k_returnPatenteGuida:
  705. [self openModel:@"patenteguida" isNew:true];
  706. break;
  707. case k_returnCartaIdentita:
  708. [self openModel:@"cartaidentita" isNew:true];
  709. break;
  710. case k_returnPassaporto:
  711. [self openModel:@"passaporto" isNew:true];
  712. break;
  713. }
  714. }
  715. #pragma --------------------------------------------------------------------------------------------
  716. #pragma mark ===== Save selected File =====
  717. #pragma --------------------------------------------------------------------------------------------
  718. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  719. {
  720. if (error)
  721. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  722. else
  723. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  724. }
  725. - (void)saveSelectedFiles
  726. {
  727. NSLog(@"[LOG] Start download selected files ...");
  728. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  729. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  730. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  731. for (CCMetadata *metadata in metadatas) {
  732. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  733. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  734. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  735. }
  736. }
  737. [_hud hideHud];
  738. });
  739. [self tableViewSelect:NO];
  740. }
  741. #pragma --------------------------------------------------------------------------------------------
  742. #pragma mark ===== Change Password =====
  743. #pragma --------------------------------------------------------------------------------------------
  744. - (void) loginSuccess:(NSInteger)loginType
  745. {
  746. [self readFolderWithForced:YES serverUrl:_serverUrl];
  747. }
  748. - (void)changePasswordAccount
  749. {
  750. // Brand
  751. if (k_option_use_login_web) {
  752. _loginWeb = [CCLoginWeb new];
  753. _loginWeb.delegate = self;
  754. _loginWeb.loginType = loginModifyPasswordUser;
  755. dispatch_async(dispatch_get_main_queue(), ^ {
  756. [_loginWeb presentModalWithDefaultTheme:self];
  757. });
  758. } else {
  759. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  760. _loginVC.delegate = self;
  761. _loginVC.loginType = loginModifyPasswordUser;
  762. [self presentViewController:_loginVC animated:YES completion:nil];
  763. }
  764. }
  765. #pragma mark -
  766. #pragma --------------------------------------------------------------------------------------------
  767. #pragma mark ===== Peek & Pop =====
  768. #pragma --------------------------------------------------------------------------------------------
  769. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  770. {
  771. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  772. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  773. if (metadata.thumbnailExists && !metadata.cryptated) {
  774. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  775. if (cell) {
  776. previewingContext.sourceRect = cell.frame;
  777. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  778. vc.delegate = self;
  779. vc.metadata = metadata;
  780. return vc;
  781. }
  782. }
  783. return nil;
  784. }
  785. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  786. {
  787. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  788. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  789. }
  790. #pragma mark -
  791. #pragma --------------------------------------------------------------------------------------------
  792. #pragma mark ==== External Sites ====
  793. #pragma --------------------------------------------------------------------------------------------
  794. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  795. {
  796. [CCCoreData deleteAllExternalSitesForAccount:app.activeAccount];
  797. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  798. [CCCoreData addExternalSites:tableExternalSites account:app.activeAccount];
  799. }
  800. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  801. {
  802. NSLog(@"[LOG] No External Sites found");
  803. }
  804. #pragma --------------------------------------------------------------------------------------------
  805. #pragma mark ==== Activity ====
  806. #pragma --------------------------------------------------------------------------------------------
  807. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  808. {
  809. for (OCActivity *activity in listOfActivity)
  810. [CCCoreData addActivityServer:activity account:app.activeAccount];
  811. // Reload Activity Data Source
  812. [app.activeActivity reloadDatasource];
  813. }
  814. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  815. {
  816. NSLog(@"[LOG] No Activity found");
  817. }
  818. #pragma --------------------------------------------------------------------------------------------
  819. #pragma mark ==== Notification ====
  820. #pragma --------------------------------------------------------------------------------------------
  821. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  822. {
  823. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  824. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  825. // Order by date
  826. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  827. OCNotifications *notification1 = obj1, *notification2 = obj2;
  828. return [notification2.date compare: notification1.date];
  829. }];
  830. // verify if listOfNotifications is changed
  831. NSString *old = @"", *new = @"";
  832. for (OCNotifications *notification in listOfNotifications)
  833. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  834. for (OCNotifications *notification in appDelegate.listOfNotifications)
  835. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  836. if (![new isEqualToString:old]) {
  837. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  838. // reload Notification view
  839. dispatch_async(dispatch_get_main_queue(), ^{
  840. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  841. });
  842. }
  843. // Update NavigationBar
  844. if (!_isSelectedMode) {
  845. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  846. }
  847. });
  848. }
  849. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  850. {
  851. // Update NavigationBar
  852. if (!_isSelectedMode)
  853. [self setUINavigationBarDefault];
  854. }
  855. - (void)viewNotification
  856. {
  857. if ([app.listOfNotifications count] > 0) {
  858. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  859. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  860. [self presentViewController:notificationVC animated:YES completion:nil];
  861. }
  862. }
  863. #pragma --------------------------------------------------------------------------------------------
  864. #pragma mark ==== Request Server ====
  865. #pragma --------------------------------------------------------------------------------------------
  866. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  867. {
  868. [CCCoreData setUserProfileActiveAccount:metadataNet.account userProfile:userProfile];
  869. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  870. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  871. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  872. if (avatar)
  873. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  874. else
  875. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  876. });
  877. }
  878. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  879. {
  880. // Change Theming color
  881. [app settingThemingColor:capabilities.themingColor];
  882. [CCCoreData addCapabilities:capabilities account:app.activeAccount];
  883. // Search bar if change version
  884. if (app.serverVersion != capabilities.versionMajor) {
  885. [self cancelSearchBar];
  886. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  887. if (capabilities.versionMajor >= 12) {
  888. if (_isRoot)
  889. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  890. else
  891. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  892. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  893. } else {
  894. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  895. self.searchController.searchBar.scopeButtonTitles = nil;
  896. }
  897. _depth = @"0";
  898. });
  899. }
  900. // External Sites
  901. if (capabilities.isExternalSitesServerEnabled) {
  902. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  903. metadataNet.action = actionGetExternalSitesServer;
  904. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  905. }
  906. [CCCoreData setServerVersionActiveAccount:app.activeAccount versionMajor:capabilities.versionMajor versionMinor:capabilities.versionMinor versionMicro:capabilities.versionMicro];
  907. app.serverVersion = capabilities.versionMajor;
  908. }
  909. - (void)getFeaturesSupportedByServerSuccess:(BOOL)hasCapabilitiesSupport hasForbiddenCharactersSupport:(BOOL)hasForbiddenCharactersSupport hasShareSupport:(BOOL)hasShareSupport hasShareeSupport:(BOOL)hasShareeSupport
  910. {
  911. app.hasServerCapabilitiesSupport = hasCapabilitiesSupport;
  912. app.hasServerForbiddenCharactersSupport = hasForbiddenCharactersSupport;
  913. app.hasServerShareSupport = hasShareSupport;
  914. app.hasServerShareeSupport = hasShareeSupport;
  915. if (hasShareSupport || hasShareeSupport)
  916. [self requestSharedByServer];
  917. }
  918. - (void)getInfoServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  919. {
  920. if (errorCode == 401)
  921. [self changePasswordAccount];
  922. }
  923. - (void)requestServerInformation
  924. {
  925. // test
  926. if (app.activeAccount.length == 0)
  927. return;
  928. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  929. [app.sharesID removeAllObjects];
  930. app.hasServerForbiddenCharactersSupport = YES;
  931. app.hasServerShareSupport = YES;
  932. metadataNet.action = actionGetFeaturesSuppServer;
  933. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  934. metadataNet.action = actionGetCapabilities;
  935. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  936. metadataNet.action = actionGetNotificationServer;
  937. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  938. metadataNet.action = actionGetUserProfile;
  939. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  940. metadataNet.action = actionGetActivityServer;
  941. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  942. }
  943. #pragma --------------------------------------------------------------------------------------------
  944. #pragma mark ==== Download Thumbnail Delegate ====
  945. #pragma --------------------------------------------------------------------------------------------
  946. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  947. {
  948. __block CCCellMain *cell;
  949. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  950. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  951. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  952. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  953. if (cell.fileImageView.image == nil) {
  954. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  955. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  956. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  957. });
  958. }
  959. }
  960. }
  961. #pragma --------------------------------------------------------------------------------------------
  962. #pragma mark ==== Download ====
  963. #pragma --------------------------------------------------------------------------------------------
  964. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  965. {
  966. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  967. // File do not exists on server, remove in local
  968. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  969. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  970. }
  971. if ([selector isEqualToString:selectorLoadViewImage]) {
  972. dispatch_async(dispatch_get_main_queue(), ^{
  973. // Updating Detail
  974. if (app.activeDetail)
  975. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  976. // Updating Photos
  977. if (app.activePhotosCameraUpload)
  978. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  979. });
  980. } else {
  981. if (errorCode != kCFURLErrorCancelled)
  982. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  983. }
  984. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  985. }
  986. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  987. {
  988. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  989. if (metadata == nil) return;
  990. // Download
  991. if ([selector isEqualToString:selectorDownloadFile]) {
  992. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  993. }
  994. // Synchronized
  995. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  996. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  997. }
  998. // add Favorite
  999. if ([selector isEqualToString:selectorAddFavorite]) {
  1000. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1001. }
  1002. // add Offline
  1003. if ([selector isEqualToString:selectorAddOffline]) {
  1004. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  1005. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1006. }
  1007. // encrypted file
  1008. if ([selector isEqualToString:selectorEncryptFile]) {
  1009. [self encryptedFile:metadata];
  1010. }
  1011. // decrypted file
  1012. if ([selector isEqualToString:selectorDecryptFile]) {
  1013. [self decryptedFile:metadata];
  1014. }
  1015. // open View File
  1016. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1017. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1018. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1019. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1020. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1021. selector = selectorOpenIn;
  1022. } else {
  1023. _metadata = metadata;
  1024. if ([self shouldPerformSegue])
  1025. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1026. }
  1027. }
  1028. // addLocal
  1029. if ([selector isEqualToString:selectorAddLocal]) {
  1030. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1031. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1032. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1033. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  1034. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1035. }
  1036. // Open with...
  1037. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1038. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1039. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1040. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1041. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1042. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1043. _docController.delegate = self;
  1044. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1045. }
  1046. // Save to Photo Album
  1047. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1048. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1049. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1050. // evitiamo il rimando photo
  1051. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  1052. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1053. if (image)
  1054. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1055. else
  1056. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1057. }
  1058. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1059. // we avoid the cross-reference video
  1060. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  1061. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1062. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1063. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1064. } else {
  1065. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1066. }
  1067. }
  1068. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1069. }
  1070. // Copy File
  1071. if ([selector isEqualToString:selectorLoadCopy]) {
  1072. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1073. [self copyFileToPasteboard:metadata];
  1074. }
  1075. // download and view a template
  1076. if ([selector isEqualToString:selectorLoadModelView]) {
  1077. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1078. [self openModel:metadata.model isNew:false];
  1079. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1080. }
  1081. //download file plist
  1082. if ([selector isEqualToString:selectorLoadPlist]) {
  1083. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1084. long countSelectorLoadPlist = 0;
  1085. for (NSOperation *operation in [app.netQueue operations]) {
  1086. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1087. countSelectorLoadPlist++;
  1088. }
  1089. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1090. dispatch_async(dispatch_get_main_queue(), ^{
  1091. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1092. });
  1093. }
  1094. }
  1095. //selectorLoadViewImage
  1096. if ([selector isEqualToString:selectorLoadViewImage]) {
  1097. dispatch_async(dispatch_get_main_queue(), ^{
  1098. // Detail
  1099. if (app.activeDetail)
  1100. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1101. // Photos
  1102. if (app.activePhotosCameraUpload)
  1103. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1104. });
  1105. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1106. }
  1107. // if exists postselector call self with selectorPost
  1108. if ([selectorPost length] > 0)
  1109. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1110. }
  1111. - (void)downloadSelectedFiles
  1112. {
  1113. NSLog(@"[LOG] Start download selected files ...");
  1114. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1115. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1116. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1117. for (CCMetadata *metadata in selectedMetadatas) {
  1118. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1119. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1120. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1121. }
  1122. }
  1123. [_hud hideHud];
  1124. });
  1125. [self tableViewSelect:NO];
  1126. }
  1127. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1128. {
  1129. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1130. for (TableMetadata *recordMetadata in records) {
  1131. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1132. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1133. metadataNet.action = actionDownloadFile;
  1134. metadataNet.metadata = [CCCoreData insertEntityInMetadata:recordMetadata];
  1135. metadataNet.downloadData = NO;
  1136. metadataNet.downloadPlist = YES;
  1137. metadataNet.selector = selectorLoadPlist;
  1138. metadataNet.serverUrl = serverUrl;
  1139. metadataNet.session = k_download_session_foreground;
  1140. metadataNet.taskStatus = k_taskStatusResume;
  1141. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1142. }
  1143. }
  1144. }
  1145. #pragma --------------------------------------------------------------------------------------------
  1146. #pragma mark ===== Upload new Photos/Videos =====
  1147. #pragma --------------------------------------------------------------------------------------------
  1148. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1149. {
  1150. // Automatic upload All
  1151. if([selector isEqualToString:selectorUploadAutomaticAll])
  1152. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1153. // Read File test do not exists
  1154. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1155. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1156. // reUpload
  1157. if (metadata)
  1158. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1159. }
  1160. // Print error
  1161. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1162. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1163. }
  1164. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1165. }
  1166. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1167. {
  1168. // Automatic upload All
  1169. if([selector isEqualToString:selectorUploadAutomaticAll])
  1170. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1171. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1172. [self readFolderWithForced:YES serverUrl:serverUrl];
  1173. } else {
  1174. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1175. }
  1176. }
  1177. //
  1178. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1179. //
  1180. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1181. {
  1182. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1183. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1184. });
  1185. }
  1186. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1187. {
  1188. NSArray *assets = [arguments objectAtIndex:0];
  1189. NSString *serverUrl = [arguments objectAtIndex:1];
  1190. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1191. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1192. NSString *session = [arguments objectAtIndex:4];
  1193. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1194. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1195. // Create the folder for Photos & if request the subfolders
  1196. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1197. return;
  1198. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1199. for (PHAsset *asset in assets) {
  1200. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1201. NSDate *assetDate = asset.creationDate;
  1202. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1203. // Create serverUrl if use sub folder
  1204. if (useSubFolder) {
  1205. [formatter setDateFormat:@"yyyy"];
  1206. NSString *yearString = [formatter stringFromDate:assetDate];
  1207. [formatter setDateFormat:@"MM"];
  1208. NSString *monthString = [formatter stringFromDate:assetDate];
  1209. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1210. }
  1211. // Check if is in upload
  1212. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@) AND (session != NULL) AND (session != '')", app.activeAccount, directoryID, fileName];
  1213. NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1214. if ([isRecordInSessions count] > 0) {
  1215. // next upload
  1216. continue;
  1217. } else {
  1218. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1219. metadataNet.action = actionReadFile;
  1220. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1221. metadataNet.cryptated = cryptated;
  1222. metadataNet.fileName = fileName;
  1223. metadataNet.priority = NSOperationQueuePriorityNormal;
  1224. metadataNet.session = session;
  1225. metadataNet.selector = selectorReadFileUploadFile;
  1226. metadataNet.serverUrl = serverUrl;
  1227. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1228. }
  1229. }
  1230. }
  1231. #pragma --------------------------------------------------------------------------------------------
  1232. #pragma mark ==== Read File ====
  1233. #pragma --------------------------------------------------------------------------------------------
  1234. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1235. {
  1236. // UploadFile
  1237. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1238. // File not exists
  1239. if (errorCode == 404) {
  1240. metadataNet.action = actionUploadAsset;
  1241. metadataNet.errorCode = 0;
  1242. metadataNet.selector = selectorUploadFile;
  1243. metadataNet.selectorPost = nil;
  1244. metadataNet.taskStatus = k_taskStatusResume;
  1245. if ([metadataNet.session containsString:@"wwan"])
  1246. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1247. else
  1248. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1249. } else {
  1250. // error ho many retry befor notification and go to on next asses
  1251. if (metadataNet.errorRetry < 3) {
  1252. // Retry read file
  1253. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1254. } else {
  1255. // STOP check file, view message error
  1256. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1257. }
  1258. }
  1259. }
  1260. }
  1261. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1262. {
  1263. // UploadFile
  1264. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1265. metadataNet.action = actionUploadAsset;
  1266. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1267. metadataNet.selector = selectorUploadFile;
  1268. metadataNet.selectorPost = nil;
  1269. metadataNet.taskStatus = k_taskStatusResume;
  1270. if ([metadataNet.session containsString:@"wwan"])
  1271. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1272. else
  1273. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1274. }
  1275. }
  1276. #pragma --------------------------------------------------------------------------------------------
  1277. #pragma mark ==== Read Folder ====
  1278. #pragma --------------------------------------------------------------------------------------------
  1279. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1280. {
  1281. // verify active user
  1282. TableAccount *record = [CCCoreData getActiveAccount];
  1283. [_hud hideHud];
  1284. [_refreshControl endRefreshing];
  1285. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1286. if (message && [record.account isEqualToString:metadataNet.account])
  1287. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1288. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1289. if (errorCode == 401)
  1290. [self changePasswordAccount];
  1291. }
  1292. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1293. {
  1294. // verify active user
  1295. TableAccount *record = [CCCoreData getActiveAccount];
  1296. if (![record.account isEqualToString:metadataNet.account])
  1297. return;
  1298. // save father e update permission
  1299. if(!_isSearchMode)
  1300. _fatherPermission = permissions;
  1301. NSArray *recordsInSessions;
  1302. if (_isSearchMode) {
  1303. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", metadataNet.account] context:nil];
  1304. } else {
  1305. [CCCoreData updateDirectoryEtagServerUrl:metadataNet.serverUrl etag:etag activeAccount:metadataNet.account];
  1306. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadataNet.directoryID]];
  1307. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (session != NULL) AND (session != '')", metadataNet.account, metadataNet.directoryID] context:nil];
  1308. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1309. }
  1310. for (CCMetadata *metadata in metadatas) {
  1311. // Delete Record only in Search Mode
  1312. if (_isSearchMode)
  1313. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileID = %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1314. // type of file
  1315. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1316. // if crypto do not insert
  1317. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1318. // verify if the record encrypted has plist + crypto
  1319. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1320. BOOL isCryptoComplete = NO;
  1321. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1322. for (CCMetadata *completeMetadata in metadatas) {
  1323. if (completeMetadata.cryptated == NO) continue;
  1324. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1325. isCryptoComplete = YES;
  1326. break;
  1327. }
  1328. }
  1329. if (isCryptoComplete == NO) continue;
  1330. }
  1331. // verify if the record is in download/upload progress
  1332. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1333. CCMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1334. // is in Upload
  1335. if (metadataDB.session && [metadataDB.session containsString:@"upload"]) {
  1336. NSString *sessionID = metadataDB.sessionID;
  1337. // rename SessionID -> fileID
  1338. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1339. metadataDB.session = @"";
  1340. metadataDB.date = metadata.date;
  1341. metadataDB.fileID = metadata.fileID;
  1342. metadataDB.rev = metadata.fileID;
  1343. metadataDB.sessionError = @"";
  1344. metadataDB.sessionID = @"";
  1345. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1346. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1347. [CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1348. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1349. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1350. continue;
  1351. }
  1352. // download in progress
  1353. if (metadataDB.session && [metadataDB.session containsString:@"download"])
  1354. continue;
  1355. }
  1356. // end test, insert in CoreData
  1357. [CCCoreData addMetadata:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1358. }
  1359. // read plist
  1360. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1361. // File is changed ??
  1362. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1363. if (!_isSearchMode)
  1364. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1365. });
  1366. // Search Mode
  1367. if (_isSearchMode)
  1368. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1369. // this is the same directory
  1370. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1371. // reload
  1372. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1373. // stoprefresh
  1374. [_refreshControl endRefreshing];
  1375. // Enable change user
  1376. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1377. [_hud hideHud];
  1378. }
  1379. }
  1380. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1381. {
  1382. // init control
  1383. if (!serverUrl || !app.activeAccount)
  1384. return;
  1385. // Search Mode
  1386. if (_isSearchMode) {
  1387. if (forced) {
  1388. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:serverUrl directoryID:nil];
  1389. _searchFileName = @""; // forced reload searchg
  1390. }
  1391. [self updateSearchResultsForSearchController:self.searchController];
  1392. return;
  1393. }
  1394. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1395. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1396. if (_refreshControl.isRefreshing == NO)
  1397. [_hud visibleIndeterminateHud];
  1398. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1399. metadataNet.action = actionReadFolder;
  1400. metadataNet.date = [NSDate date];
  1401. metadataNet.directoryID = directoryID;
  1402. metadataNet.priority = NSOperationQueuePriorityHigh;
  1403. metadataNet.selector = selectorReadFolder;
  1404. metadataNet.serverUrl = serverUrl;
  1405. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1406. }
  1407. }
  1408. #pragma mark -
  1409. #pragma --------------------------------------------------------------------------------------------
  1410. #pragma mark ===== Search =====
  1411. #pragma --------------------------------------------------------------------------------------------
  1412. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1413. {
  1414. _isSearchMode = YES;
  1415. [self deleteRefreshControl];
  1416. NSString *fileName = [CCUtility removeForbiddenCharacters:searchController.searchBar.text hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1417. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1418. _searchFileName = fileName;
  1419. if (app.serverVersion >= 12 && ![_depth isEqualToString:@"0"]) {
  1420. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1421. _noFilesSearchTitle = @"";
  1422. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1423. [self.tableView reloadEmptyDataSet];
  1424. } else {
  1425. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1426. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(directoryID == %@) AND (account == %@) AND (fileNamePrint CONTAINS[cd] %@)", directoryID, app.activeAccount, fileName];
  1427. NSArray *records = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1428. [_searchResultMetadatas removeAllObjects];
  1429. for (TableMetadata *record in records)
  1430. [_searchResultMetadatas addObject:[CCCoreData insertEntityInMetadata:record]];
  1431. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1432. metadataNet.account = app.activeAccount;
  1433. metadataNet.action = actionUploadTemplate;
  1434. metadataNet.directoryID = directoryID;
  1435. metadataNet.selector = selectorSearch;
  1436. metadataNet.serverUrl = _serverUrl;
  1437. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1438. }
  1439. }
  1440. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1441. [self reloadDatasource];
  1442. }
  1443. }
  1444. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1445. {
  1446. [self cancelSearchBar];
  1447. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1448. }
  1449. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1450. {
  1451. _searchFileName = @"";
  1452. if (message)
  1453. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1454. }
  1455. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1456. {
  1457. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1458. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1459. }
  1460. - (void)cancelSearchBar
  1461. {
  1462. if (self.searchController.active) {
  1463. [self.searchController setActive:NO];
  1464. [self createRefreshControl];
  1465. _isSearchMode = NO;
  1466. _searchFileName = @"";
  1467. _dateReadDataSource = nil;
  1468. _searchResultMetadatas = [NSMutableArray new];
  1469. [self reloadDatasource];
  1470. }
  1471. }
  1472. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1473. {
  1474. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1475. self.searchController.searchBar.placeholder = title;
  1476. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1477. _depth = @"0";
  1478. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1479. _depth = @"1";
  1480. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1481. _depth = @"infinity";
  1482. _searchFileName = @"";
  1483. [self updateSearchResultsForSearchController:self.searchController];
  1484. }
  1485. #pragma mark -
  1486. #pragma --------------------------------------------------------------------------------------------
  1487. #pragma mark ===== Delete File or Folder =====
  1488. #pragma --------------------------------------------------------------------------------------------
  1489. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1490. {
  1491. [self deleteFileOrFolderSuccess:metadataNet];
  1492. }
  1493. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1494. {
  1495. [_queueSelector removeObject:metadataNet.selector];
  1496. if ([_queueSelector count] == 0) {
  1497. [_hud hideHud];
  1498. if (_isSearchMode)
  1499. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1500. else
  1501. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.metadata.fileID selector:metadataNet.selector];
  1502. // next
  1503. if ([_selectedMetadatas count] > 0) {
  1504. [_selectedMetadatas removeObjectAtIndex:0];
  1505. if ([_selectedMetadatas count] > 0)
  1506. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1507. }
  1508. }
  1509. }
  1510. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1511. {
  1512. if (metadata.cryptated) {
  1513. [_queueSelector addObject:selectorDeleteCrypto];
  1514. [_queueSelector addObject:selectorDeletePlist];
  1515. } else {
  1516. [_queueSelector addObject:selectorDelete];
  1517. }
  1518. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1519. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1520. }
  1521. - (void)deleteSelectionFile
  1522. {
  1523. [_selectedMetadatas removeAllObjects];
  1524. [_queueSelector removeAllObjects];
  1525. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1526. _numSelectedMetadatas = [_selectedMetadatas count];
  1527. if ([_selectedMetadatas count] > 0)
  1528. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1529. [self tableViewSelect:NO];
  1530. }
  1531. - (void)deleteFile
  1532. {
  1533. [_selectedMetadatas removeAllObjects];
  1534. [_queueSelector removeAllObjects];
  1535. _numSelectedMetadatas = 1;
  1536. [_selectedMetadatas addObject:_metadata];
  1537. if ([_selectedMetadatas count] > 0)
  1538. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1539. [self tableViewSelect:NO];
  1540. }
  1541. #pragma --------------------------------------------------------------------------------------------
  1542. #pragma mark ===== Rename / Move =====
  1543. #pragma --------------------------------------------------------------------------------------------
  1544. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1545. {
  1546. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1547. }
  1548. - (void)renameFile:(CCMetadata *)metadata fileName:(NSString *)fileName
  1549. {
  1550. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1551. }
  1552. - (void)renameNote:(CCMetadata *)metadata fileName:(NSString *)fileName
  1553. {
  1554. CCTemplates *templates = [[CCTemplates alloc] init];
  1555. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1556. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1557. if (fileNameModel) {
  1558. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1559. metadataNet.action = actionUploadTemplate;
  1560. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1561. metadataNet.fileNamePrint = fileName;
  1562. metadataNet.rev = metadata.rev;
  1563. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1564. metadataNet.session = k_upload_session_foreground;
  1565. metadataNet.taskStatus = k_taskStatusResume;
  1566. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1567. metadataNet.selectorPost = selectorAddOffline;
  1568. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1569. }
  1570. }
  1571. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1572. {
  1573. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1574. [_hud hideHud];
  1575. if (message)
  1576. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1577. [_selectedMetadatas removeAllObjects];
  1578. [_queueSelector removeAllObjects];
  1579. }
  1580. }
  1581. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1582. {
  1583. [_queueSelector removeObject:metadataNet.selector];
  1584. if ([_queueSelector count] == 0) {
  1585. [_hud hideHud];
  1586. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1587. NSString *directoryID = metadataNet.directoryID;
  1588. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1589. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1590. // FILE -> Metadata
  1591. if (metadataNet.directory == NO) {
  1592. // move metadata
  1593. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1594. }
  1595. // DIRECTORY -> Directory - CCMetadata
  1596. if (metadataNet.directory == YES) {
  1597. // delete all dir / subdir
  1598. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName] activeAccount:app.activeAccount];
  1599. // delete all metadata and local file in dir / subdir
  1600. for (NSString *directoryIDDelete in directoryIDs)
  1601. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1602. // move metadata
  1603. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1604. // Add new directory
  1605. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1606. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1607. // Check Offline
  1608. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1609. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1610. }
  1611. // reload Datasource
  1612. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1613. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1614. else
  1615. [self reloadDatasource];
  1616. // Next file
  1617. [_selectedMetadatas removeObjectAtIndex:0];
  1618. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1619. }
  1620. }
  1621. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1622. {
  1623. if ([_selectedMetadatas count] > 0) {
  1624. CCMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1625. // Plain
  1626. if (metadata.cryptated == NO) {
  1627. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1628. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1629. if(!error) {
  1630. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1631. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1632. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1633. }];
  1634. [alert addAction:ok];
  1635. [self presentViewController:alert animated:YES completion:nil];
  1636. });
  1637. return;
  1638. }
  1639. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1640. metadataNet.action = actionMoveFileOrFolder;
  1641. metadataNet.directory = metadata.directory;
  1642. metadataNet.fileID = metadata.fileID;
  1643. metadataNet.directoryID = metadata.directoryID;
  1644. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1645. metadataNet.fileName = metadata.fileName;
  1646. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1647. metadataNet.fileNameTo = metadata.fileName;
  1648. metadataNet.rev = metadata.rev;
  1649. metadataNet.selector = selectorMove;
  1650. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1651. metadataNet.serverUrlTo = serverUrlTo;
  1652. [_queueSelector addObject:metadataNet.selector];
  1653. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1654. }
  1655. // cyptated
  1656. if (metadata.cryptated == YES) {
  1657. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1658. metadataNet.action = actionMoveFileOrFolder;
  1659. metadataNet.directory = metadata.directory;
  1660. metadataNet.fileID = metadata.fileID;
  1661. metadataNet.directoryID = metadata.directoryID;
  1662. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1663. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1664. metadataNet.rev = metadata.rev;
  1665. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1666. metadataNet.serverUrlTo = serverUrlTo;
  1667. // data
  1668. metadataNet.fileName = metadata.fileNameData;
  1669. metadataNet.fileNameTo = metadata.fileNameData;
  1670. metadataNet.selector = selectorMoveCrypto;
  1671. [_queueSelector addObject:metadataNet.selector];
  1672. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1673. // plist
  1674. metadataNet.fileName = metadata.fileName;
  1675. metadataNet.fileNameTo = metadata.fileName;
  1676. metadataNet.selector = selectorMovePlist;
  1677. [_queueSelector addObject:metadataNet.selector];
  1678. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1679. }
  1680. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1681. }
  1682. }
  1683. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1684. {
  1685. [_selectedMetadatas removeAllObjects];
  1686. [_queueSelector removeAllObjects];
  1687. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1688. _numSelectedMetadatas = [_selectedMetadatas count];
  1689. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1690. [self tableViewSelect:NO];
  1691. }
  1692. - (void)moveOpenWindow:(NSArray *)indexPaths
  1693. {
  1694. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1695. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1696. viewController.delegate = self;
  1697. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1698. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1699. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1700. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1701. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1702. viewController.networkingOperationQueue = app.netQueue;
  1703. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1704. [self presentViewController:navigationController animated:YES completion:nil];
  1705. }
  1706. #pragma --------------------------------------------------------------------------------------------
  1707. #pragma mark ===== Create folder =====
  1708. #pragma --------------------------------------------------------------------------------------------
  1709. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1710. {
  1711. [_hud hideHud];
  1712. if (message)
  1713. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1714. }
  1715. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1716. {
  1717. [_hud hideHud];
  1718. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1719. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1720. // Check Offline
  1721. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1722. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1723. // Load Folder or the Datasource
  1724. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1725. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1726. } else {
  1727. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1728. }
  1729. }
  1730. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1731. {
  1732. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1733. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1734. if (![fileNameFolder length]) return;
  1735. if (folderCameraUpload) metadataNet.serverUrl = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1736. else metadataNet.serverUrl = _serverUrl;
  1737. metadataNet.action = actionCreateFolder;
  1738. if (folderCameraUpload)
  1739. metadataNet.options = @"folderCameraUpload";
  1740. metadataNet.fileName = fileNameFolder;
  1741. metadataNet.selector = selectorCreateFolder;
  1742. metadataNet.selectorPost = selectorReadFolderForced;
  1743. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1744. if (!folderCameraUpload)
  1745. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1746. }
  1747. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1748. {
  1749. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1750. NSString *fileNamePlist;
  1751. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1752. if (![fileNameFolder length]) return;
  1753. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1754. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1755. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1756. // Create folder
  1757. metadataNet.action = actionCreateFolder;
  1758. metadataNet.fileName = fileNamePlist;
  1759. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1760. metadataNet.selector = selectorCreateFolder;
  1761. metadataNet.serverUrl = _serverUrl;
  1762. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1763. // upload plist file
  1764. metadataNet.action = actionUploadOnlyPlist;
  1765. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1766. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1767. metadataNet.selectorPost = selectorReadFolderForced;
  1768. metadataNet.serverUrl = _serverUrl;
  1769. metadataNet.session = k_upload_session_foreground;
  1770. metadataNet.taskStatus = k_taskStatusResume;
  1771. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1772. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1773. }
  1774. - (void)createFolderCameraUpload
  1775. {
  1776. [self createFolder:[CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount] folderCameraUpload:YES];
  1777. }
  1778. #pragma --------------------------------------------------------------------------------------------
  1779. #pragma mark ===== Encrypted / Decrypted Folder =====
  1780. #pragma --------------------------------------------------------------------------------------------
  1781. - (void)encyptedDecryptedFolder
  1782. {
  1783. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1784. if (_metadata.cryptated) {
  1785. // DECRYPTED
  1786. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1787. //-------------------------- RENAME -------------------------------------------//
  1788. metadataNet.action = actionMoveFileOrFolder;
  1789. metadataNet.fileID = _metadata.fileID;
  1790. metadataNet.fileName = _metadata.fileNameData;
  1791. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1792. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1793. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1794. metadataNet.selector = selectorRename;
  1795. metadataNet.serverUrl = serverUrl;
  1796. metadataNet.serverUrlTo = serverUrl;
  1797. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1798. //-------------------------- DELETE -------------------------------------------//
  1799. metadataNet.action = actionDeleteFileDirectory;
  1800. metadataNet.fileID = _metadata.fileID;
  1801. metadataNet.fileName = _metadata.fileName;
  1802. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1803. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1804. metadataNet.selector = selectorDeletePlist;
  1805. metadataNet.selectorPost = selectorReadFolderForced;
  1806. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1807. } else {
  1808. // ENCRYPTED
  1809. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1810. // Create File Plist
  1811. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1812. //-------------------------- RENAME -------------------------------------------//
  1813. metadataNet.action = actionMoveFileOrFolder;
  1814. metadataNet.fileID = _metadata.fileID;
  1815. metadataNet.fileName = _metadata.fileName;
  1816. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1817. metadataNet.fileNameTo = fileNameCrypto;
  1818. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1819. metadataNet.selector = selectorRename;
  1820. metadataNet.serverUrl = serverUrl;
  1821. metadataNet.serverUrlTo = serverUrl;
  1822. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1823. //-------------------------- UPLOAD -------------------------------------------//
  1824. metadataNet.action = actionUploadOnlyPlist;
  1825. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1826. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1827. metadataNet.selectorPost = selectorReadFolderForced;
  1828. metadataNet.serverUrl = serverUrl;
  1829. metadataNet.session = k_upload_session_foreground;
  1830. metadataNet.taskStatus = k_taskStatusResume;
  1831. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1832. }
  1833. }
  1834. #pragma --------------------------------------------------------------------------------------------
  1835. #pragma mark ===== Encrypted/Decrypted File =====
  1836. #pragma --------------------------------------------------------------------------------------------
  1837. - (void)encryptedSelectedFiles
  1838. {
  1839. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1840. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1841. for (CCMetadata *metadata in selectedMetadatas) {
  1842. if (metadata.cryptated == NO && metadata.directory == NO)
  1843. [metadatas addObject:metadata];
  1844. }
  1845. if ([metadatas count] > 0) {
  1846. NSLog(@"[LOG] Start encrypted selected files ...");
  1847. for (CCMetadata* metadata in metadatas) {
  1848. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1849. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1850. }
  1851. }
  1852. [self tableViewSelect:NO];
  1853. }
  1854. - (void)decryptedSelectedFiles
  1855. {
  1856. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1857. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1858. for (CCMetadata *metadata in selectedMetadatas) {
  1859. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1860. [metadatas addObject:metadata];
  1861. }
  1862. if ([metadatas count] > 0) {
  1863. NSLog(@"[LOG] Start decrypted selected files ...");
  1864. for (CCMetadata* metadata in metadatas) {
  1865. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1866. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1867. }
  1868. }
  1869. [self tableViewSelect:NO];
  1870. }
  1871. - (void)cmdEncryptedDecryptedFile
  1872. {
  1873. NSString *selector;
  1874. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1875. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1876. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1877. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1878. }
  1879. - (void)encryptedFile:(CCMetadata *)metadata
  1880. {
  1881. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1882. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1883. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1884. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1885. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1886. dispatch_async(dispatch_get_main_queue(), ^{
  1887. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1888. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1889. });
  1890. } else {
  1891. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1892. }
  1893. }
  1894. - (void)decryptedFile:(CCMetadata *)metadata
  1895. {
  1896. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1897. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1898. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1899. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1900. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1901. dispatch_async(dispatch_get_main_queue(), ^{
  1902. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1903. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1904. });
  1905. } else {
  1906. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1907. }
  1908. }
  1909. #pragma --------------------------------------------------------------------------------------------
  1910. #pragma mark ===== Progress & Task Button =====
  1911. #pragma --------------------------------------------------------------------------------------------
  1912. - (void)triggerProgressTask:(NSNotification *)notification
  1913. {
  1914. NSDictionary *dict = notification.userInfo;
  1915. NSString *fileID = [dict valueForKey:@"fileID"];
  1916. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1917. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1918. float progress = [[dict valueForKey:@"progress"] floatValue];
  1919. // Check
  1920. if (!fileID)
  1921. return;
  1922. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1923. if (![serverUrl isEqualToString:_serverUrl])
  1924. return;
  1925. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1926. if (indexPath) {
  1927. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1928. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1929. else cell.progressView.progressTintColor = [UIColor blackColor];
  1930. cell.progressView.hidden = NO;
  1931. [cell.progressView setProgress:progress];
  1932. }
  1933. if (progress == 0)
  1934. [self.navigationController cancelCCProgress];
  1935. else
  1936. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1937. }
  1938. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1939. {
  1940. UITouch * touch = [[event allTouches] anyObject];
  1941. CGPoint location = [touch locationInView:self.tableView];
  1942. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1943. if (indexPath) {
  1944. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1945. if (metadata)
  1946. [self reloadTaskButton:metadata];
  1947. }
  1948. }
  1949. - (void)reloadTaskButton:(CCMetadata *)metadata
  1950. {
  1951. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1952. __block NSURLSessionTask *findTask;
  1953. // DOWNLOAD
  1954. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1955. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1956. for (NSURLSessionUploadTask *task in downloadTasks)
  1957. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1958. findTask = task;
  1959. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1960. [task cancel];
  1961. }
  1962. if (!findTask) {
  1963. dispatch_async(dispatch_get_main_queue(), ^{
  1964. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1965. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1966. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1967. });
  1968. }
  1969. }];
  1970. }
  1971. // UPLOAD
  1972. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1973. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1974. for (NSURLSessionUploadTask *task in uploadTasks)
  1975. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1976. findTask = task;
  1977. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1978. [task cancel];
  1979. }
  1980. if (!findTask) {
  1981. dispatch_async(dispatch_get_main_queue(), ^{
  1982. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1983. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1984. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1985. });
  1986. }
  1987. }];
  1988. }
  1989. }
  1990. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1991. {
  1992. UITouch * touch = [[event allTouches] anyObject];
  1993. CGPoint location = [touch locationInView:self.tableView];
  1994. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1995. if (indexPath) {
  1996. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1997. if (metadata)
  1998. [self cancelTaskButton:metadata reloadTable:YES];
  1999. }
  2000. }
  2001. - (void)cancelTaskButton:(CCMetadata *)metadata reloadTable:(BOOL)reloadTable
  2002. {
  2003. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2004. __block NSURLSessionTask *findTask;
  2005. // DOWNLOAD
  2006. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2007. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2008. for (NSURLSessionTask *task in downloadTasks)
  2009. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2010. findTask = task;
  2011. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2012. [task cancel];
  2013. }
  2014. if (!findTask) {
  2015. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2016. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2017. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2018. }
  2019. }];
  2020. }
  2021. // UPLOAD
  2022. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2023. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2024. for (NSURLSessionUploadTask *task in uploadTasks)
  2025. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2026. findTask = task;
  2027. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2028. [task cancel];
  2029. }
  2030. if (!findTask) {
  2031. dispatch_async(dispatch_get_main_queue(), ^{
  2032. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2033. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2034. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2035. });
  2036. }
  2037. }];
  2038. }
  2039. }
  2040. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2041. {
  2042. UITouch * touch = [[event allTouches] anyObject];
  2043. CGPoint location = [touch locationInView:self.tableView];
  2044. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2045. if (indexPath) {
  2046. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2047. if (metadata)
  2048. [self stopTaskButton:metadata];
  2049. }
  2050. }
  2051. - (void)stopTaskButton:(CCMetadata *)metadata
  2052. {
  2053. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2054. __block NSURLSessionTask *findTask;
  2055. // UPLOAD
  2056. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2057. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2058. for (NSURLSessionUploadTask *task in uploadTasks)
  2059. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2060. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2061. findTask = task;
  2062. [task cancel];
  2063. }
  2064. if (!findTask) {
  2065. dispatch_async(dispatch_get_main_queue(), ^{
  2066. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2067. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2068. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2069. });
  2070. }
  2071. }];
  2072. }
  2073. }
  2074. #pragma --------------------------------------------------------------------------------------------
  2075. #pragma mark ===== Shared =====
  2076. #pragma --------------------------------------------------------------------------------------------
  2077. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2078. {
  2079. [_hud hideHud];
  2080. // change account ?
  2081. TableAccount *record = [CCCoreData getActiveAccount];
  2082. if([record.account isEqualToString:metadataNet.account] == NO)
  2083. return;
  2084. [CCCoreData updateShare:items sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount activeUrl:app.activeUrl];
  2085. if (openWindow) {
  2086. if (_shareOC) {
  2087. [_shareOC reloadData];
  2088. } else {
  2089. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2090. // Apriamo la view
  2091. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2092. _shareOC.delegate = self;
  2093. _shareOC.metadata = metadata;
  2094. _shareOC.serverUrl = metadataNet.serverUrl;
  2095. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2096. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2097. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2098. [self presentViewController:_shareOC animated:YES completion:nil];
  2099. }
  2100. }
  2101. [self tableViewReload];
  2102. }
  2103. - (void)requestSharedByServer
  2104. {
  2105. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2106. metadataNet.action = actionReadShareServer;
  2107. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2108. }
  2109. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2110. {
  2111. [_hud hideHud];
  2112. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2113. if (_shareOC)
  2114. [_shareOC reloadData];
  2115. [self tableViewReload];
  2116. if (errorCode == 401)
  2117. [self changePasswordAccount];
  2118. }
  2119. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2120. {
  2121. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2122. metadataNet.action = actionShare;
  2123. metadataNet.fileID = metadata.fileID;
  2124. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2125. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2126. metadataNet.password = password;
  2127. metadataNet.selector = selectorShare;
  2128. metadataNet.serverUrl = serverUrl;
  2129. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2130. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2131. }
  2132. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2133. {
  2134. [_hud hideHud];
  2135. // rimuoviamo la condivisione da db
  2136. [CCCoreData unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount];
  2137. if (_shareOC)
  2138. [_shareOC reloadData];
  2139. [self tableViewReload];
  2140. }
  2141. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2142. {
  2143. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2144. metadataNet.action = actionUnShare;
  2145. metadataNet.fileID = metadata.fileID;
  2146. metadataNet.fileName = metadata.fileName;
  2147. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2148. metadataNet.selector = selectorUnshare;
  2149. metadataNet.serverUrl = serverUrl;
  2150. metadataNet.share = share;
  2151. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2152. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2153. }
  2154. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2155. {
  2156. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2157. metadataNet.action = actionUpdateShare;
  2158. metadataNet.fileID = metadata.fileID;
  2159. metadataNet.expirationTime = expirationTime;
  2160. metadataNet.password = password;
  2161. metadataNet.selector = selectorUpdateShare;
  2162. metadataNet.serverUrl = serverUrl;
  2163. metadataNet.share = share;
  2164. metadataNet.sharePermission = permission;
  2165. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2166. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2167. }
  2168. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2169. {
  2170. [_hud hideHud];
  2171. if (_shareOC)
  2172. [_shareOC reloadUserAndGroup:items];
  2173. }
  2174. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2175. {
  2176. [_hud hideHud];
  2177. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2178. }
  2179. - (void)getUserAndGroup:(NSString *)find
  2180. {
  2181. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2182. metadataNet.action = actionGetUserAndGroup;
  2183. metadataNet.options = find;
  2184. metadataNet.selector = selectorGetUserAndGroup;
  2185. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2186. [_hud visibleIndeterminateHud];
  2187. }
  2188. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2189. {
  2190. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2191. metadataNet.action = actionShareWith;
  2192. metadataNet.fileID = metadata.fileID;
  2193. metadataNet.directoryID = directoryID;
  2194. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2195. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2196. metadataNet.serverUrl = serverUrl;
  2197. metadataNet.selector = selectorShare;
  2198. metadataNet.share = user;
  2199. metadataNet.shareeType = shareeType;
  2200. metadataNet.sharePermission = permission;
  2201. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2202. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2203. }
  2204. - (void)openWindowShare:(CCMetadata *)metadata
  2205. {
  2206. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2207. metadataNet.action = actionReadShareServer;
  2208. metadataNet.fileID = metadata.fileID;
  2209. metadataNet.fileName = metadata.fileName;
  2210. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2211. metadataNet.selector = selectorOpenWindowShare;
  2212. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2213. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2214. [_hud visibleIndeterminateHud];
  2215. }
  2216. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2217. {
  2218. CGPoint location = [tapGesture locationInView:self.tableView];
  2219. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2220. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2221. if (metadata)
  2222. [self openWindowShare:metadata];
  2223. }
  2224. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2225. {
  2226. CGPoint location = [tapGesture locationInView:self.tableView];
  2227. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2228. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2229. if (metadata) {
  2230. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2231. vc.metadata = metadata;
  2232. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2233. [self presentViewController:vc animated:YES completion:nil];
  2234. }
  2235. }
  2236. #pragma --------------------------------------------------------------------------------------------
  2237. #pragma mark ===== Favorite =====
  2238. #pragma --------------------------------------------------------------------------------------------
  2239. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2240. {
  2241. [CCCoreData setMetadataFavoriteFileID:metadataNet.fileID favorite:[metadataNet.options boolValue] activeAccount:app.activeAccount context:nil];
  2242. _dateReadDataSource = nil;
  2243. if (_isSearchMode)
  2244. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2245. else
  2246. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2247. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2248. if (metadata.directory && metadata.favorite) {
  2249. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2250. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2251. }
  2252. }
  2253. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2254. {
  2255. }
  2256. - (void)addFavorite:(CCMetadata *)metadata
  2257. {
  2258. if (metadata.directory) {
  2259. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2260. } else {
  2261. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2262. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2263. }
  2264. }
  2265. - (void)removeFavorite:(CCMetadata *)metadata
  2266. {
  2267. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2268. }
  2269. #pragma --------------------------------------------------------------------------------------------
  2270. #pragma mark ===== Offline =====
  2271. #pragma --------------------------------------------------------------------------------------------
  2272. - (void)addOffline:(CCMetadata *)metadata
  2273. {
  2274. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2275. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2276. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2277. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2278. }
  2279. - (void)removeOffline:(CCMetadata *)metadata
  2280. {
  2281. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2282. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2283. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2284. }
  2285. #pragma --------------------------------------------------------------------------------------------
  2286. #pragma mark ===== Local =====
  2287. #pragma --------------------------------------------------------------------------------------------
  2288. - (void)addLocal:(CCMetadata *)metadata
  2289. {
  2290. if (metadata.errorPasscode || !metadata.uuid) return;
  2291. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2292. if ([metadata.type isEqualToString: k_metadataType_file])
  2293. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2294. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2295. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2296. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  2297. }
  2298. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2299. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2300. }
  2301. #pragma --------------------------------------------------------------------------------------------
  2302. #pragma mark ===== Open in... =====
  2303. #pragma --------------------------------------------------------------------------------------------
  2304. - (void)openIn:(CCMetadata *)metadata
  2305. {
  2306. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2307. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2308. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2309. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2310. }
  2311. #pragma --------------------------------------------------------------------------------------------
  2312. #pragma mark ===== Remove Local File =====
  2313. #pragma --------------------------------------------------------------------------------------------
  2314. - (void)removeLocalFile:(CCMetadata *)metadata
  2315. {
  2316. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2317. [CCCoreData deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@)", app.activeAccount, metadata.fileID]];
  2318. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2319. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2320. }
  2321. #pragma --------------------------------------------------------------------------------------------
  2322. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2323. #pragma --------------------------------------------------------------------------------------------
  2324. - (void)orderTable:(NSString *)order
  2325. {
  2326. [CCUtility setOrderSettings:order];
  2327. // Clear data-read of DataSource
  2328. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2329. // new menu
  2330. [self createReMainMenu];
  2331. }
  2332. - (void)ascendingTable:(BOOL)ascending
  2333. {
  2334. [CCUtility setAscendingSettings:ascending];
  2335. // Clear data-read of DataSource
  2336. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2337. // new menu
  2338. [self createReMainMenu];
  2339. }
  2340. - (void)directoryOnTop:(BOOL)directoryOnTop
  2341. {
  2342. [CCUtility setDirectoryOnTop:directoryOnTop];
  2343. // Clear data-read of DataSource
  2344. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2345. // new menu
  2346. [self createReMainMenu];
  2347. }
  2348. - (void)tableGroupBy:(NSString *)groupBy
  2349. {
  2350. [CCUtility setGroupBySettings:groupBy];
  2351. // Clear data-read of DataSource
  2352. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2353. // new menu
  2354. [self createReMainMenu];
  2355. }
  2356. #pragma --------------------------------------------------------------------------------------------
  2357. #pragma mark ==== Menu LOGO ====
  2358. #pragma --------------------------------------------------------------------------------------------
  2359. - (void)menuLogo
  2360. {
  2361. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2362. return;
  2363. // Brand
  2364. if (k_option_disable_multiaccount)
  2365. return;
  2366. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [CCCoreData countTableAutomaticUploadForAccount:app.activeAccount selector:nil] > 0) {
  2367. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  2368. return;
  2369. }
  2370. NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2371. NSMutableArray *menuArray = [NSMutableArray new];
  2372. for (TableAccount *record in listTableAccount) {
  2373. if ([record.account isEqualToString:app.activeAccount]) continue;
  2374. CCMenuItem *item = [[CCMenuItem alloc] init];
  2375. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2376. item.argument = record.account;
  2377. item.image = [UIImage imageNamed:image_MenuLogoUser];
  2378. item.target = self;
  2379. item.action = @selector(changeDefaultAccount:);
  2380. [menuArray addObject:item];
  2381. }
  2382. if ([menuArray count] == 0)
  2383. return;
  2384. OptionalConfiguration options;
  2385. Color textColor, backgroundColor;
  2386. textColor.R = 0;
  2387. textColor.G = 0;
  2388. textColor.B = 0;
  2389. backgroundColor.R = 1;
  2390. backgroundColor.G = 1;
  2391. backgroundColor.B = 1;
  2392. NSInteger originY = 60;
  2393. options.arrowSize = 9;
  2394. options.marginXSpacing = 7;
  2395. options.marginYSpacing = 10;
  2396. options.intervalSpacing = 20;
  2397. options.menuCornerRadius = 6.5;
  2398. options.maskToBackground = NO;
  2399. options.shadowOfMenu = YES;
  2400. options.hasSeperatorLine = YES;
  2401. options.seperatorLineHasInsets = YES;
  2402. options.textColor = textColor;
  2403. options.menuBackgroundColor = backgroundColor;
  2404. CGRect rect = self.view.frame;
  2405. rect.origin.y = rect.origin.y + originY;
  2406. rect.size.height = rect.size.height - originY;
  2407. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2408. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2409. }
  2410. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2411. {
  2412. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2413. // STOP, erase all in queue networking
  2414. [app cancelAllOperations];
  2415. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2416. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2417. TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2418. if (tableAccount)
  2419. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2420. // go to home sweet home
  2421. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2422. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2423. });
  2424. }
  2425. #pragma --------------------------------------------------------------------------------------------
  2426. #pragma mark ==== ReMenu ====
  2427. #pragma --------------------------------------------------------------------------------------------
  2428. - (void)createReMenuBackgroundView:(REMenu *)menu
  2429. {
  2430. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2431. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2432. [UIView animateWithDuration:0.2 animations:^{
  2433. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2434. if (height < self.tabBarController.tabBar.frame.size.height)
  2435. height = self.tabBarController.tabBar.frame.size.height;
  2436. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2437. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2438. }];
  2439. }
  2440. - (void)createReMainMenu
  2441. {
  2442. NSString *ordinamento;
  2443. NSString *groupBy = _directoryGroupBy;
  2444. __block NSString *nuovoOrdinamento;
  2445. NSString *titoloNuovo, *titoloAttuale;
  2446. BOOL ascendente;
  2447. __block BOOL nuovoAscendente;
  2448. UIImage *image;
  2449. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2450. if (app.selezionaItem == nil) app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_seleziona] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2451. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2452. [self tableViewSelect:YES];
  2453. }
  2454. }];
  2455. else app.selezionaItem = [app.selezionaItem initWithTitle:NSLocalizedString(@"_select_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_seleziona] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2456. if ([_sectionDataSource.allRecordsDataSource count] > 0)
  2457. [self tableViewSelect:YES];
  2458. }];
  2459. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2460. ordinamento = _directoryOrder;
  2461. if ([ordinamento isEqualToString:@"fileName"]) {
  2462. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdeyByDate] color:[NCBrandColor sharedInstance].brand];
  2463. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2464. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2465. nuovoOrdinamento = @"fileDate";
  2466. }
  2467. if ([ordinamento isEqualToString:@"fileDate"]) {
  2468. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrderByFileName] color:[NCBrandColor sharedInstance].brand];
  2469. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2470. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2471. nuovoOrdinamento = @"fileName";
  2472. }
  2473. if (app.ordinaItem == nil) app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2474. [self orderTable:nuovoOrdinamento];
  2475. }];
  2476. else app.ordinaItem = [app.ordinaItem initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2477. [self orderTable:nuovoOrdinamento];
  2478. }];
  2479. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2480. ascendente = [CCUtility getAscendingSettings];
  2481. if (ascendente) {
  2482. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdinamentoDiscendente] color:[NCBrandColor sharedInstance].brand];
  2483. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2484. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2485. nuovoAscendente = false;
  2486. }
  2487. if (!ascendente) {
  2488. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdinamentoAscendente] color:[NCBrandColor sharedInstance].brand];
  2489. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2490. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2491. nuovoAscendente = true;
  2492. }
  2493. if (app.ascendenteItem == nil) app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2494. [self ascendingTable:nuovoAscendente];
  2495. }];
  2496. else app.ascendenteItem = [app.ascendenteItem initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2497. [self ascendingTable:nuovoAscendente];
  2498. }];
  2499. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2500. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2501. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2502. if (app.alphabeticItem == nil) app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByAlphabetic] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2503. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2504. else [self tableGroupBy:@"alphabetic"];
  2505. }];
  2506. else app.alphabeticItem = [app.alphabeticItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByAlphabetic] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2507. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2508. else [self tableGroupBy:@"alphabetic"];
  2509. }];
  2510. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2511. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2512. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2513. if (app.typefileItem == nil) app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByTypeFile] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2514. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2515. else [self tableGroupBy:@"typefile"];
  2516. }];
  2517. else app.typefileItem = [app.typefileItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByTypeFile] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2518. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2519. else [self tableGroupBy:@"typefile"];
  2520. }];
  2521. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2522. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2523. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2524. if (app.dateItem == nil) app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByDate] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2525. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2526. else [self tableGroupBy:@"date"];
  2527. }];
  2528. else app.dateItem = [app.dateItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByDate] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2529. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2530. else [self tableGroupBy:@"date"];
  2531. }];
  2532. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2533. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2534. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2535. if (app.directoryOnTopItem == nil) app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuDirectoryOnTop] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2536. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2537. else [self directoryOnTop:YES];
  2538. }];
  2539. else app.directoryOnTopItem = [app.directoryOnTopItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuDirectoryOnTop] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2540. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2541. else [self directoryOnTop:YES];
  2542. }];
  2543. // REMENU --------------------------------------------------------------------------------------------------------------
  2544. if (app.reMainMenu == nil) app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2545. else app.reMainMenu = [app.reMainMenu initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2546. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2547. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2548. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2549. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2550. app.reMainMenu.separatorHeight = 0.5;
  2551. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2552. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2553. app.reMainMenu.textColor = [UIColor blackColor];
  2554. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2555. app.reMainMenu.textShadowColor = nil;
  2556. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2557. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2558. app.reMainMenu.highlightedBackgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  2559. app.reMainMenu.highlightedSeparatorColor = nil;
  2560. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2561. app.reMainMenu.highlightedTextShadowColor = nil;
  2562. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2563. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2564. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2565. app.reMainMenu.subtitleTextShadowColor = nil;
  2566. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2567. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2568. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2569. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2570. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2571. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2572. app.reMainMenu.borderWidth = 0.3;
  2573. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2574. app.reMainMenu.animationDuration = 0.2;
  2575. app.reMainMenu.closeAnimationDuration = 0.2;
  2576. app.reMainMenu.bounce = NO;
  2577. [app.reMainMenu setClosePreparationBlock:^{
  2578. // Backgroun reMenu (Gesture)
  2579. [_reMenuBackgroundView removeFromSuperview];
  2580. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2581. }];
  2582. }
  2583. - (void)toggleReMainMenu
  2584. {
  2585. if (app.reMainMenu.isOpen) {
  2586. [app.reMainMenu close];
  2587. } else {
  2588. [app.reMainMenu showFromNavigationController:self.navigationController];
  2589. // Backgroun reMenu & (Gesture)
  2590. [self createReMenuBackgroundView:app.reMainMenu];
  2591. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2592. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2593. }
  2594. }
  2595. - (void)createReSelectMenu
  2596. {
  2597. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2598. if (app.deleteItem == nil) app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_deleteSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2599. [self deleteSelectionFile];
  2600. }];
  2601. else app.deleteItem = [app.deleteItem initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_deleteSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2602. [self deleteSelectionFile];
  2603. }];
  2604. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2605. if (app.moveItem == nil) app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_moveSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2606. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2607. }];
  2608. else app.moveItem = [app.moveItem initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_moveSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2609. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2610. }];
  2611. if (app.isCryptoCloudMode) {
  2612. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2613. if (app.encryptItem == nil) app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_encryptedSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2614. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2615. }];
  2616. else app.encryptItem = [app.encryptItem initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_encryptedSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2617. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2618. }];
  2619. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2620. if (app.decryptItem == nil) app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_decryptedSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2621. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2622. }];
  2623. else app.decryptItem = [app.decryptItem initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_decryptedSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2624. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2625. }];
  2626. }
  2627. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2628. if (app.downloadItem == nil) app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_downloadSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2629. [self downloadSelectedFiles];
  2630. }];
  2631. else app.downloadItem = [app.downloadItem initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_downloadSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2632. [self downloadSelectedFiles];
  2633. }];
  2634. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2635. if (app.saveItem == nil) app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_saveSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2636. [self saveSelectedFiles];
  2637. }];
  2638. else app.saveItem = [app.saveItem initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_saveSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2639. [self saveSelectedFiles];
  2640. }];
  2641. // REMENU --------------------------------------------------------------------------------------------------------------
  2642. if (app.isCryptoCloudMode) {
  2643. if (app.reSelectMenu == nil)
  2644. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2645. else
  2646. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2647. } else {
  2648. if (app.reSelectMenu == nil)
  2649. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2650. else
  2651. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2652. }
  2653. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2654. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2655. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2656. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2657. app.reSelectMenu.separatorHeight = 0.5;
  2658. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2659. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2660. app.reSelectMenu.textColor = [UIColor blackColor];
  2661. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2662. app.reSelectMenu.textShadowColor = nil;
  2663. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2664. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2665. app.reSelectMenu.highlightedBackgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  2666. app.reSelectMenu.highlightedSeparatorColor = nil;
  2667. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2668. app.reSelectMenu.highlightedTextShadowColor = nil;
  2669. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2670. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2671. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2672. app.reSelectMenu.subtitleTextShadowColor = nil;
  2673. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2674. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2675. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2676. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2677. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2678. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2679. app.reSelectMenu.borderWidth = 0.3;
  2680. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2681. app.reSelectMenu.closeAnimationDuration = 0.2;
  2682. app.reSelectMenu.animationDuration = 0.2;
  2683. app.reSelectMenu.bounce = NO;
  2684. [app.reSelectMenu setClosePreparationBlock:^{
  2685. // Backgroun reMenu (Gesture)
  2686. [_reMenuBackgroundView removeFromSuperview];
  2687. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2688. }];
  2689. }
  2690. - (void)toggleReSelectMenu
  2691. {
  2692. if (app.reSelectMenu.isOpen) {
  2693. [app.reSelectMenu close];
  2694. } else {
  2695. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2696. // Backgroun reMenu & (Gesture)
  2697. [self createReMenuBackgroundView:app.reSelectMenu];
  2698. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2699. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2700. }
  2701. }
  2702. #pragma --------------------------------------------------------------------------------------------
  2703. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2704. #pragma --------------------------------------------------------------------------------------------
  2705. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2706. {
  2707. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2708. UITableView *tableView = (UITableView*)self.view;
  2709. CGPoint touchPoint = [recognizer locationInView:self.view];
  2710. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2711. if (indexPath)
  2712. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2713. else
  2714. _metadata = nil;
  2715. [self becomeFirstResponder];
  2716. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2717. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2718. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2719. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2720. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2721. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2722. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2723. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2724. if (app.isCryptoCloudMode)
  2725. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2726. else
  2727. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2728. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2729. [menuController setMenuVisible:YES animated:YES];
  2730. }
  2731. }
  2732. - (BOOL)canBecomeFirstResponder
  2733. {
  2734. return YES;
  2735. }
  2736. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2737. {
  2738. // For copy file, copy files, Open in ... :
  2739. //
  2740. // NO Directory
  2741. // NO Error Passcode
  2742. // NO In Session mode (download/upload)
  2743. // NO Template
  2744. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2745. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2746. // NO Cryptated with Title lenght = 0
  2747. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2748. return YES;
  2749. }
  2750. return NO;
  2751. }
  2752. if (@selector(copyFiles:) == action) {
  2753. if (_isSelectedMode) {
  2754. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2755. for (CCMetadata *metadata in selectedMetadatas) {
  2756. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2757. // NO Cryptated with Title lenght = 0
  2758. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2759. return YES;
  2760. }
  2761. }
  2762. }
  2763. return NO;
  2764. }
  2765. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2766. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2767. NSArray *items = [pasteboard items];
  2768. if ([items count] == 1) {
  2769. // Value : (NSData) metadata
  2770. NSDictionary *dic = [items objectAtIndex:0];
  2771. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2772. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2773. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2774. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2775. if (directoryUser) {
  2776. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2777. return YES;
  2778. }
  2779. return NO;
  2780. } else return NO;
  2781. }
  2782. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2783. BOOL isValid = NO;
  2784. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2785. NSArray *items = [pasteboard items];
  2786. if ([items count] <= 1) return NO;
  2787. for (NSDictionary *dic in items) {
  2788. // Value : (NSData) metadata
  2789. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2790. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2791. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2792. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2793. if (directoryUser) {
  2794. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2795. isValid = YES;
  2796. }
  2797. }
  2798. return isValid;
  2799. }
  2800. return NO;
  2801. }
  2802. /************************************ COPY ************************************/
  2803. - (void)copyFile:(id)sender
  2804. {
  2805. // Remove all item
  2806. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2807. pasteboard.items = [[NSArray alloc] init];
  2808. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2809. [self copyFileToPasteboard:_metadata];
  2810. } else {
  2811. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2812. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2813. }
  2814. }
  2815. - (void)copyFiles:(id)sender
  2816. {
  2817. // Remove all item
  2818. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2819. pasteboard.items = [[NSArray alloc] init];
  2820. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2821. for (CCMetadata *metadata in selectedMetadatas) {
  2822. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2823. [self copyFileToPasteboard:metadata];
  2824. } else {
  2825. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2826. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2827. }
  2828. }
  2829. [self tableViewSelect:NO];
  2830. }
  2831. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2832. {
  2833. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2834. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2835. // Value : (NSData) metadata
  2836. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], k_metadataKeyedUnarchiver,nil];
  2837. [items addObject:item];
  2838. [pasteboard setItems:items];
  2839. }
  2840. /************************************ OPEN IN ... ************************************/
  2841. - (void)openinFile:(id)sender
  2842. {
  2843. [self openIn:_metadata];
  2844. }
  2845. /************************************ PASTE ************************************/
  2846. - (void)pasteFile:(id)sender
  2847. {
  2848. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2849. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2850. }
  2851. - (void)pasteFileEncrypted:(id)sender
  2852. {
  2853. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2854. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2855. }
  2856. - (void)pasteFiles:(id)sender
  2857. {
  2858. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2859. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2860. }
  2861. - (void)pasteFilesEncrypted:(id)sender
  2862. {
  2863. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2864. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2865. }
  2866. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2867. {
  2868. for (NSDictionary *dic in items) {
  2869. // Value : (NSData) metadata
  2870. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2871. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2872. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2873. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2874. if (directoryUser) {
  2875. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2876. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2877. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2878. }
  2879. }
  2880. }
  2881. }
  2882. #pragma --------------------------------------------------------------------------------------------
  2883. #pragma mark ===== Lock Passcode =====
  2884. #pragma --------------------------------------------------------------------------------------------
  2885. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2886. {
  2887. return _failedAttempts;
  2888. }
  2889. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2890. {
  2891. return _lockUntilDate;
  2892. }
  2893. - (void)passcodeViewCloseButtonPressed:(id)sender
  2894. {
  2895. [self dismissViewControllerAnimated:YES completion:nil];
  2896. }
  2897. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2898. {
  2899. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2900. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2901. _lockUntilDate = nil;
  2902. _failedAttempts = 0;
  2903. aResultHandler(YES);
  2904. } else aResultHandler(NO);
  2905. } else aResultHandler(YES);
  2906. }
  2907. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2908. {
  2909. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2910. switch (aViewController.type) {
  2911. case BKPasscodeViewControllerCheckPasscodeType: {
  2912. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2913. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2914. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2915. // scriviamo il passcode
  2916. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2917. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2918. } else {
  2919. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2920. [alertView show];
  2921. }
  2922. }
  2923. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2924. // possiamo procedere alla prossima directory
  2925. [self performSegueDirectoryWithControlPasscode:false];
  2926. // avviamo la sessione Passcode Lock con now
  2927. app.sessionePasscodeLock = [NSDate date];
  2928. }
  2929. // disattivazione lock cartella
  2930. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2931. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2932. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2933. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2934. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2935. }
  2936. [self.tableView reloadData];
  2937. }
  2938. }
  2939. break;
  2940. default:
  2941. break;
  2942. }
  2943. }
  2944. - (void)comandoLockPassword
  2945. {
  2946. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2947. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2948. // se non è abilitato il Lock Passcode esci
  2949. if ([[CCUtility getBlockCode] length] == 0) {
  2950. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2951. [alertView show];
  2952. return;
  2953. }
  2954. // se è richiesta la disattivazione si chiede la password
  2955. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2956. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2957. viewController.delegate = self;
  2958. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2959. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2960. viewController.inputViewTitlePassword = YES;
  2961. if ([CCUtility getSimplyBlockCode]) {
  2962. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2963. viewController.passcodeInputView.maximumLength = 6;
  2964. } else {
  2965. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2966. viewController.passcodeInputView.maximumLength = 64;
  2967. }
  2968. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2969. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2970. viewController.touchIDManager = touchIDManager;
  2971. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2972. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2973. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2974. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2975. [self presentViewController:navigationController animated:YES completion:nil];
  2976. return;
  2977. }
  2978. // ---------------- ACTIVATE PASSWORD
  2979. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2980. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2981. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2982. } else {
  2983. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2984. }
  2985. }
  2986. #pragma mark -
  2987. #pragma --------------------------------------------------------------------------------------------
  2988. #pragma mark ===== Swipe Tablet -> menu =====
  2989. #pragma --------------------------------------------------------------------------------------------
  2990. // more
  2991. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2992. return NSLocalizedString(@"_more_", nil);
  2993. }
  2994. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2995. {
  2996. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2997. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2998. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder, *titleFavorite;
  2999. BOOL offlineFolder = NO;
  3000. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3001. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3002. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3003. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3004. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3005. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  3006. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3007. offlineFolder = YES;
  3008. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3009. if (_metadata.favorite) {
  3010. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3011. } else {
  3012. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3013. }
  3014. if (_metadata.directory) {
  3015. // calcolo lockServerUrl
  3016. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3017. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3018. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3019. }
  3020. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:_metadata.fileID activeAccount:app.activeAccount];
  3021. /******************************************* AHKActionSheet *******************************************/
  3022. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3023. actionSheet.animationDuration = 0.2;
  3024. actionSheet.blurRadius = 0.0f;
  3025. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3026. actionSheet.buttonHeight = 50.0;
  3027. actionSheet.cancelButtonHeight = 50.0f;
  3028. actionSheet.separatorHeight = 5.0f;
  3029. actionSheet.automaticallyTintButtonImages = @(NO);
  3030. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3031. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3032. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3033. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3034. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3035. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3036. /******************************************* DIRECTORY *******************************************/
  3037. if (_metadata.directory) {
  3038. BOOL lockDirectory = NO;
  3039. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3040. // Directory bloccata ?
  3041. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3042. NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3043. NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3044. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3045. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3046. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3047. height: 50.0
  3048. type: AHKActionSheetButtonTypeDisabled
  3049. handler: nil
  3050. ];
  3051. if (!lockDirectory && !_metadata.cryptated) {
  3052. [actionSheet addButtonWithTitle:titleFavorite
  3053. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetFavorite] color:[NCBrandColor sharedInstance].brand]
  3054. backgroundColor:[UIColor whiteColor]
  3055. height: 50.0
  3056. type:AHKActionSheetButtonTypeDefault
  3057. handler:^(AHKActionSheet *as) {
  3058. // close swipe
  3059. [self setEditing:NO animated:YES];
  3060. if (_metadata.favorite)
  3061. [self removeFavorite:_metadata];
  3062. else
  3063. [self addFavorite:_metadata];
  3064. }];
  3065. }
  3066. if (_metadata.cryptated == NO && app.hasServerShareSupport && !lockDirectory) {
  3067. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3068. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:[NCBrandColor sharedInstance].brand]
  3069. backgroundColor:[UIColor whiteColor]
  3070. height: 50.0
  3071. type:AHKActionSheetButtonTypeDefault
  3072. handler:^(AHKActionSheet *as) {
  3073. // close swipe
  3074. [self setEditing:NO animated:YES];
  3075. [self openWindowShare:_metadata];
  3076. }];
  3077. }
  3078. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3079. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3080. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRename] color:[NCBrandColor sharedInstance].brand]
  3081. backgroundColor:[UIColor whiteColor]
  3082. height: 50.0
  3083. type:AHKActionSheetButtonTypeDefault
  3084. handler:^(AHKActionSheet *as) {
  3085. // close swipe
  3086. [self setEditing:NO animated:YES];
  3087. //chiediamo il nome del file
  3088. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3089. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3090. alertView.tag = alertRename;
  3091. UITextField *textField = [alertView textFieldAtIndex:0];
  3092. textField.text = _metadata.fileNamePrint;
  3093. [alertView show];
  3094. }];
  3095. }
  3096. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3097. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3098. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetMove] color:[NCBrandColor sharedInstance].brand]
  3099. backgroundColor:[UIColor whiteColor]
  3100. height: 50.0
  3101. type:AHKActionSheetButtonTypeDefault
  3102. handler:^(AHKActionSheet *as) {
  3103. // close swipe
  3104. [self setEditing:NO animated:YES];
  3105. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3106. }];
  3107. }
  3108. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3109. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3110. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folderphotocamera] color:[NCBrandColor sharedInstance].brand]
  3111. backgroundColor:[UIColor whiteColor]
  3112. height: 50.0
  3113. type:AHKActionSheetButtonTypeDefault
  3114. handler:^(AHKActionSheet *as) {
  3115. // close swipe
  3116. [self setEditing:NO animated:YES];
  3117. // Settings new folder Automatatic upload
  3118. NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3119. [CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3120. [CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl activeAccount:app.activeAccount];
  3121. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:oldPath directoryID:nil];
  3122. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3123. [app.activePhotosCameraUpload reloadDatasourceForced];
  3124. [self readFolderWithForced:YES serverUrl:serverUrl];
  3125. NSLog(@"[LOG] Update Folder Photo");
  3126. NSString *folderCameraUpload = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3127. if ([folderCameraUpload length] > 0)
  3128. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:app.activeAccount] selector:selectorReadFolder];
  3129. }];
  3130. }
  3131. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3132. [actionSheet addButtonWithTitle:titoloLock
  3133. image:[UIImage imageNamed:image_actionSheetLock]
  3134. backgroundColor:[UIColor whiteColor]
  3135. height: 50.0
  3136. type:AHKActionSheetButtonTypeEncrypted
  3137. handler:^(AHKActionSheet *as) {
  3138. // close swipe
  3139. [self setEditing:NO animated:YES];
  3140. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3141. }];
  3142. }
  3143. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3144. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3145. image:[UIImage imageNamed:image_actionSheetCrypto]
  3146. backgroundColor:[UIColor whiteColor]
  3147. height: 50.0
  3148. type:AHKActionSheetButtonTypeEncrypted
  3149. handler:^(AHKActionSheet *as) {
  3150. // close swipe
  3151. [self setEditing:NO animated:YES];
  3152. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3153. }];
  3154. }
  3155. [actionSheet show];
  3156. }
  3157. /******************************************* FILE *******************************************/
  3158. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3159. UIImage *iconHeader;
  3160. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3161. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3162. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3163. else
  3164. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3165. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3166. image: iconHeader
  3167. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3168. height: 50.0
  3169. type: AHKActionSheetButtonTypeDisabled
  3170. handler: nil
  3171. ];
  3172. if (!_metadata.cryptated) {
  3173. [actionSheet addButtonWithTitle:titleFavorite
  3174. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetFavorite] color:[NCBrandColor sharedInstance].brand]
  3175. backgroundColor:[UIColor whiteColor]
  3176. height: 50.0
  3177. type:AHKActionSheetButtonTypeDefault
  3178. handler:^(AHKActionSheet *as) {
  3179. // close swipe
  3180. [self setEditing:NO animated:YES];
  3181. if (_metadata.favorite)
  3182. [self removeFavorite:_metadata];
  3183. else
  3184. [self addFavorite:_metadata];
  3185. }];
  3186. }
  3187. if (_metadata.cryptated == NO && app.hasServerShareSupport) {
  3188. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3189. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:[NCBrandColor sharedInstance].brand]
  3190. backgroundColor:[UIColor whiteColor]
  3191. height: 50.0
  3192. type:AHKActionSheetButtonTypeDefault
  3193. handler:^(AHKActionSheet *as) {
  3194. // close swipe
  3195. [self setEditing:NO animated:YES];
  3196. [self openWindowShare:_metadata];
  3197. }];
  3198. }
  3199. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3200. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetOpenIn] color:[NCBrandColor sharedInstance].brand]
  3201. backgroundColor:[UIColor whiteColor]
  3202. height: 50.0
  3203. type:AHKActionSheetButtonTypeDefault
  3204. handler:^(AHKActionSheet *as) {
  3205. // close swipe
  3206. [self setEditing:NO animated:YES];
  3207. [self performSelector:@selector(openIn:) withObject:_metadata];
  3208. }];
  3209. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3210. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRename] color:[NCBrandColor sharedInstance].brand]
  3211. backgroundColor:[UIColor whiteColor]
  3212. height: 50.0
  3213. type:AHKActionSheetButtonTypeDefault
  3214. handler:^(AHKActionSheet *as) {
  3215. // close swipe
  3216. [self setEditing:NO animated:YES];
  3217. //chiediamo il nome del file
  3218. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3219. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3220. alertView.tag = alertRename;
  3221. UITextField *textField = [alertView textFieldAtIndex:0];
  3222. textField.text = _metadata.fileNamePrint;
  3223. [alertView show];
  3224. }];
  3225. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3226. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetMove] color:[NCBrandColor sharedInstance].brand]
  3227. backgroundColor:[UIColor whiteColor]
  3228. height: 50.0
  3229. type:AHKActionSheetButtonTypeDefault
  3230. handler:^(AHKActionSheet *as) {
  3231. // close swipe
  3232. [self setEditing:NO animated:YES];
  3233. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3234. }];
  3235. if (recordLocalFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3236. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3237. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRemoveLocal] color:[NCBrandColor sharedInstance].brand]
  3238. backgroundColor:[UIColor whiteColor]
  3239. height: 50.0
  3240. type:AHKActionSheetButtonTypeDefault
  3241. handler:^(AHKActionSheet *as) {
  3242. // close swipe
  3243. [self setEditing:NO animated:YES];
  3244. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3245. }];
  3246. }
  3247. if (app.isCryptoCloudMode) {
  3248. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3249. image:[UIImage imageNamed:image_actionSheetCrypto]
  3250. backgroundColor:[UIColor whiteColor]
  3251. height: 50.0
  3252. type:AHKActionSheetButtonTypeEncrypted
  3253. handler:^(AHKActionSheet *as) {
  3254. // close swipe
  3255. [self setEditing:NO animated:YES];
  3256. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3257. }];
  3258. }
  3259. [actionSheet show];
  3260. }
  3261. /******************************************* TEMPLATE *******************************************/
  3262. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3263. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3264. image: [UIImage imageNamed:_metadata.iconName]
  3265. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3266. height: 50.0
  3267. type: AHKActionSheetButtonTypeDisabled
  3268. handler: nil
  3269. ];
  3270. if ([_metadata.model isEqualToString:@"note"]) {
  3271. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3272. image:[UIImage imageNamed:image_actionSheetRename]
  3273. backgroundColor:[UIColor whiteColor]
  3274. height: 50.0
  3275. type:AHKActionSheetButtonTypeDefault
  3276. handler:^(AHKActionSheet *as) {
  3277. // close swipe
  3278. [self setEditing:NO animated:YES];
  3279. //chiediamo il nome del file
  3280. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3281. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3282. alertView.tag = alertRename;
  3283. UITextField *textField = [alertView textFieldAtIndex:0];
  3284. textField.text = _metadata.fileNamePrint;
  3285. [alertView show];
  3286. }];
  3287. }
  3288. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3289. image:[UIImage imageNamed:image_actionSheetMove]
  3290. backgroundColor:[UIColor whiteColor]
  3291. height: 50.0
  3292. type:AHKActionSheetButtonTypeDefault
  3293. handler:^(AHKActionSheet *as) {
  3294. // close swipe
  3295. [self setEditing:NO animated:YES];
  3296. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3297. }];
  3298. [actionSheet show];
  3299. }
  3300. }
  3301. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3302. {
  3303. return NSLocalizedString(@"_delete_", nil);
  3304. }
  3305. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3306. {
  3307. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3308. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3309. else return YES;
  3310. }
  3311. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3312. {
  3313. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3314. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3315. else return UITableViewCellEditingStyleDelete;
  3316. }
  3317. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3318. {
  3319. BOOL lockDirectory = NO;
  3320. // Directory locked ?
  3321. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addFileName:_metadata.fileNameData];
  3322. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3323. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3324. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  3325. return;
  3326. }
  3327. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3328. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3329. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3330. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3331. style:UIAlertActionStyleDestructive
  3332. handler:^(UIAlertAction *action) {
  3333. [self performSelector:@selector(deleteFile) withObject:nil];
  3334. }]];
  3335. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3336. style:UIAlertActionStyleCancel
  3337. handler:^(UIAlertAction *action) {
  3338. [alertController dismissViewControllerAnimated:YES completion:nil];
  3339. }]];
  3340. alertController.popoverPresentationController.sourceView = self.view;
  3341. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3342. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3343. [alertController.view layoutIfNeeded];
  3344. [self presentViewController:alertController animated:YES completion:nil];
  3345. }
  3346. }
  3347. #pragma --------------------------------------------------------------------------------------------
  3348. #pragma mark - ==== Datasource ====
  3349. #pragma --------------------------------------------------------------------------------------------
  3350. - (void)clearDateReadDataSource:(NSNotification *)notification
  3351. {
  3352. _dateReadDataSource = Nil;
  3353. [self reloadDatasource];
  3354. }
  3355. - (void)reloadDatasource
  3356. {
  3357. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3358. }
  3359. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3360. {
  3361. // test
  3362. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3363. return;
  3364. // Search Mode
  3365. if(_isSearchMode) {
  3366. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3367. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3368. } else {
  3369. [self readFolderWithForced:NO serverUrl:serverUrl];
  3370. }
  3371. [self tableViewReload];
  3372. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3373. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3374. _noFilesSearchDescription = @"";
  3375. }
  3376. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3377. _noFilesSearchTitle = @"";
  3378. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3379. }
  3380. [self.tableView reloadEmptyDataSet];
  3381. return;
  3382. }
  3383. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3384. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3385. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3386. [app.activeTransfers reloadDatasource];
  3387. } else {
  3388. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3389. if (main) {
  3390. [main reloadDatasource];
  3391. } else {
  3392. [self tableViewReload];
  3393. [app.activeTransfers reloadDatasource];
  3394. }
  3395. }
  3396. return;
  3397. }
  3398. // Offline folder ?
  3399. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3400. [app.activeTransfers reloadDatasource];
  3401. // Settaggio variabili per le ottimizzazioni
  3402. _directoryGroupBy = [CCUtility getGroupBySettings];
  3403. _directoryOrder = [CCUtility getOrderSettings];
  3404. // Controllo data lettura Data Source
  3405. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3406. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3407. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3408. _dateReadDataSource = [NSDate date];
  3409. // Data Source
  3410. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3411. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3412. } else {
  3413. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3414. }
  3415. [self tableViewReload];
  3416. }
  3417. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3418. {
  3419. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3420. if (selectedRows.count > 0) {
  3421. for (NSIndexPath *selectionIndex in selectedRows) {
  3422. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3423. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3424. [metadatas addObject:metadata];
  3425. }
  3426. }
  3427. return metadatas;
  3428. }
  3429. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3430. {
  3431. NSInteger section = indexPath.section + 1;
  3432. NSInteger row = indexPath.row + 1;
  3433. NSInteger totSections =[_sectionDataSource.sections count] ;
  3434. if ((totSections < section) || (section > totSections)) {
  3435. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3436. return nil;
  3437. }
  3438. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3439. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3440. if (fileIDs) {
  3441. NSInteger totRows =[fileIDs count] ;
  3442. if ((totRows < row) || (row > totRows)) {
  3443. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3444. return nil;
  3445. }
  3446. } else {
  3447. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3448. return nil;
  3449. }
  3450. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3451. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3452. }
  3453. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3454. {
  3455. NSInteger totSections =[_sectionDataSource.sections count] ;
  3456. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3457. #if DEBUG
  3458. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3459. [alertView show];
  3460. #endif
  3461. return nil;
  3462. }
  3463. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3464. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3465. }
  3466. #pragma --------------------------------------------------------------------------------------------
  3467. #pragma mark - ==== Table ====
  3468. #pragma --------------------------------------------------------------------------------------------
  3469. - (void)tableViewSelect:(BOOL)edit
  3470. {
  3471. // chiudiamo eventuali swipe aperti
  3472. if (edit) [self.tableView setEditing:NO animated:NO];
  3473. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3474. [self.tableView setEditing:edit animated:YES];
  3475. _isSelectedMode = edit;
  3476. if (edit)
  3477. [self setUINavigationBarSelected];
  3478. else
  3479. [self setUINavigationBarDefault];
  3480. [self setTitle];
  3481. }
  3482. - (void)tableViewReload
  3483. {
  3484. // ricordiamoci le row selezionate
  3485. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3486. [self.tableView reloadData];
  3487. for (NSIndexPath *path in indexPaths)
  3488. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3489. [self setTableViewFooter];
  3490. if (self.tableView.editing)
  3491. [self setTitle];
  3492. }
  3493. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3494. {
  3495. return 60;
  3496. }
  3497. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3498. {
  3499. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3500. }
  3501. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3502. {
  3503. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3504. }
  3505. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3506. {
  3507. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3508. NSString *sectionTitle = [sections objectAtIndex:section];
  3509. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3510. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3511. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3512. return 20.f;
  3513. }
  3514. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3515. {
  3516. float shift;
  3517. UIVisualEffectView *visualEffectView;
  3518. // Titolo
  3519. NSString *titleSection;
  3520. // Controllo
  3521. if ([_sectionDataSource.sections count] == 0)
  3522. return nil;
  3523. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3524. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3525. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3526. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3527. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3528. else titleSection = NSLocalizedString(titleSection,nil);
  3529. // Formato titolo
  3530. NSString *currentDevice = [CCUtility currentDevice];
  3531. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3532. visualEffectView = [[UIVisualEffectView alloc] init];
  3533. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3534. } else {
  3535. UIVisualEffect *blurEffect;
  3536. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3537. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3538. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3539. }
  3540. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3541. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3542. else shift = - 20;
  3543. } else shift = - 10;
  3544. // Title
  3545. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3546. titleLabel.backgroundColor = [UIColor clearColor];
  3547. titleLabel.textColor = [UIColor blackColor];
  3548. titleLabel.font = [UIFont systemFontOfSize:12];
  3549. titleLabel.textAlignment = NSTextAlignmentLeft;
  3550. titleLabel.text = titleSection;
  3551. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3552. [visualEffectView addSubview:titleLabel];
  3553. // Elements
  3554. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3555. elementLabel.backgroundColor = [UIColor clearColor];
  3556. elementLabel.textColor = [UIColor blackColor];;
  3557. elementLabel.font = [UIFont systemFontOfSize:12];
  3558. elementLabel.textAlignment = NSTextAlignmentRight;
  3559. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3560. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3561. NSUInteger rowsCount = [metadatas count];
  3562. if (rowsCount == 0) return nil;
  3563. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3564. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3565. [visualEffectView addSubview:elementLabel];
  3566. return visualEffectView;
  3567. }
  3568. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3569. {
  3570. return [_sectionDataSource.sections indexOfObject:title];
  3571. }
  3572. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3573. {
  3574. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3575. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3576. else
  3577. return nil;
  3578. }
  3579. /*
  3580. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3581. {
  3582. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3583. }
  3584. }
  3585. */
  3586. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3587. {
  3588. NSString *typeCell;
  3589. NSString *dataFile;
  3590. NSString *lunghezzaFile;
  3591. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3592. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3593. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3594. else typeCell = @"CellMainTransfer";
  3595. if (!metadata)
  3596. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3597. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3598. // separator
  3599. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3600. // change color selection
  3601. UIView *selectionColor = [[UIView alloc] init];
  3602. selectionColor.backgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  3603. cell.selectedBackgroundView = selectionColor;
  3604. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3605. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3606. // ----------------------------------------------------------------------------------------------------------
  3607. // DEFAULT
  3608. // ----------------------------------------------------------------------------------------------------------
  3609. cell.fileImageView.image = nil;
  3610. cell.statusImageView.image = nil;
  3611. cell.offlineImageView.image = nil;
  3612. cell.synchronizedImageView.image = nil;
  3613. cell.sharedImageView.image = nil;
  3614. cell.labelTitle.enabled = YES;
  3615. cell.labelTitle.text = @"";
  3616. cell.labelInfoFile.enabled = YES;
  3617. cell.labelInfoFile.text = @"";
  3618. cell.progressView.progress = 0.0;
  3619. cell.progressView.hidden = YES;
  3620. cell.cancelTaskButton.hidden = YES;
  3621. cell.reloadTaskButton.hidden = YES;
  3622. cell.stopTaskButton.hidden = YES;
  3623. // Encrypted color
  3624. if (metadata.cryptated) {
  3625. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3626. } else {
  3627. cell.labelTitle.textColor = [UIColor blackColor];
  3628. }
  3629. // ----------------------------------------------------------------------------------------------------------
  3630. // File Name & Folder
  3631. // ----------------------------------------------------------------------------------------------------------
  3632. // nome del file
  3633. cell.labelTitle.text = metadata.fileNamePrint;
  3634. // è una directory
  3635. if (metadata.directory) {
  3636. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3637. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3638. lunghezzaFile = @" ";
  3639. // ----------------------------------------------------------------------------------------------------------
  3640. // Favorite Folder
  3641. // ----------------------------------------------------------------------------------------------------------
  3642. if (metadata.favorite) {
  3643. cell.offlineImageView.image = [UIImage imageNamed:image_favorite];
  3644. }
  3645. } else {
  3646. // File
  3647. dataFile = [CCUtility dateDiff:metadata.date];
  3648. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3649. // Plist ancora da scaricare
  3650. if (metadata.cryptated && [metadata.title length] == 0) {
  3651. dataFile = @" ";
  3652. lunghezzaFile = @" ";
  3653. }
  3654. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3655. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3656. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3657. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3658. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3659. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3660. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3661. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3662. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3663. else
  3664. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3665. }
  3666. // Plist ancora da scaricare
  3667. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3668. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3669. cell.accessoryType = UITableViewCellAccessoryNone;
  3670. }
  3671. // ----------------------------------------------------------------------------------------------------------
  3672. // File Image View
  3673. // ----------------------------------------------------------------------------------------------------------
  3674. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3675. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3676. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3677. if (cell.fileImageView.image == nil) {
  3678. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3679. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3680. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3681. dispatch_async(dispatch_get_main_queue(), ^{
  3682. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3683. if (cell)
  3684. cell.fileImageView.image = image;
  3685. });
  3686. });
  3687. }
  3688. } else {
  3689. if (metadata.directory)
  3690. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3691. else
  3692. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3693. if (metadata.thumbnailExists)
  3694. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3695. }
  3696. // ----------------------------------------------------------------------------------------------------------
  3697. // Image Status cyptated & Lock Passcode
  3698. // ----------------------------------------------------------------------------------------------------------
  3699. // File Cyptated
  3700. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3701. cell.statusImageView.image = [UIImage imageNamed:image_lock];
  3702. }
  3703. // Directory con passcode lock attivato
  3704. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3705. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length]))
  3706. cell.statusImageView.image = [UIImage imageNamed:image_passcode];
  3707. // ----------------------------------------------------------------------------------------------------------
  3708. // Offline
  3709. // ----------------------------------------------------------------------------------------------------------
  3710. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3711. if (isOfflineFile) {
  3712. cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3713. }
  3714. // ----------------------------------------------------------------------------------------------------------
  3715. // Favorite
  3716. // ----------------------------------------------------------------------------------------------------------
  3717. if (metadata.favorite) {
  3718. cell.offlineImageView.image = [UIImage imageNamed:image_favorite];
  3719. }
  3720. // ----------------------------------------------------------------------------------------------------------
  3721. // Share
  3722. // ----------------------------------------------------------------------------------------------------------
  3723. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3724. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3725. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3726. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3727. // Aggiungiamo il Tap per le shared
  3728. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3729. if (isShare) {
  3730. if (metadata.directory) {
  3731. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_shared_with_me] color:[NCBrandColor sharedInstance].brand];
  3732. cell.sharedImageView.userInteractionEnabled = NO;
  3733. } else {
  3734. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:[NCBrandColor sharedInstance].brand];
  3735. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3736. [tap setNumberOfTapsRequired:1];
  3737. cell.sharedImageView.userInteractionEnabled = YES;
  3738. [cell.sharedImageView addGestureRecognizer:tap];
  3739. }
  3740. }
  3741. if (isMounted) {
  3742. if (metadata.directory) {
  3743. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_external] color:[NCBrandColor sharedInstance].brand];
  3744. cell.sharedImageView.userInteractionEnabled = NO;
  3745. } else {
  3746. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_shareMounted] color:[NCBrandColor sharedInstance].brand];
  3747. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3748. [tap setNumberOfTapsRequired:1];
  3749. cell.sharedImageView.userInteractionEnabled = YES;
  3750. [cell.sharedImageView addGestureRecognizer:tap];
  3751. }
  3752. }
  3753. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3754. if (metadata.directory) {
  3755. if ([shareLink length] > 0)
  3756. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_public] color:[NCBrandColor sharedInstance].brand];
  3757. if ([shareUserAndGroup length] > 0)
  3758. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_shared_with_me] color:[NCBrandColor sharedInstance].brand];
  3759. cell.sharedImageView.userInteractionEnabled = NO;
  3760. } else {
  3761. if ([shareLink length] > 0)
  3762. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_shareLink] color:[NCBrandColor sharedInstance].brand];
  3763. if ([shareUserAndGroup length] > 0)
  3764. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:[NCBrandColor sharedInstance].brand];
  3765. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3766. [tap setNumberOfTapsRequired:1];
  3767. cell.sharedImageView.userInteractionEnabled = YES;
  3768. [cell.sharedImageView addGestureRecognizer:tap];
  3769. }
  3770. }
  3771. } else {
  3772. cell.sharedImageView.userInteractionEnabled = NO;
  3773. }
  3774. // ----------------------------------------------------------------------------------------------------------
  3775. // downloadFile
  3776. // ----------------------------------------------------------------------------------------------------------
  3777. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3778. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusdownloadcrypto];
  3779. else cell.statusImageView.image = [UIImage imageNamed:image_statusdownload];
  3780. // sessionTaskIdentifier : RELOAD + STOP
  3781. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3782. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3783. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3784. cell.cancelTaskButton.hidden = NO;
  3785. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3786. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3787. cell.reloadTaskButton.hidden = NO;
  3788. }
  3789. // sessionTaskIdentifierPlist : RELOAD
  3790. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3791. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3792. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3793. cell.reloadTaskButton.hidden = NO;
  3794. }
  3795. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3796. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3797. if (progress > 0) {
  3798. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3799. else cell.progressView.progressTintColor = [UIColor blackColor];
  3800. cell.progressView.progress = progress;
  3801. cell.progressView.hidden = NO;
  3802. }
  3803. // ----------------------------------------------------------------------------------------------------------
  3804. // downloadFile Error
  3805. // ----------------------------------------------------------------------------------------------------------
  3806. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3807. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3808. if ([metadata.sessionError length] == 0)
  3809. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3810. else
  3811. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3812. }
  3813. }
  3814. // ----------------------------------------------------------------------------------------------------------
  3815. // uploadFile
  3816. // ----------------------------------------------------------------------------------------------------------
  3817. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3818. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusuploadcrypto];
  3819. else cell.statusImageView.image = [UIImage imageNamed:image_statusupload];
  3820. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetaskcrypto] forState:UIControlStateNormal];
  3821. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetask] forState:UIControlStateNormal];
  3822. cell.cancelTaskButton.hidden = NO;
  3823. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3824. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3825. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3826. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusstopcrypto];
  3827. else cell.statusImageView.image = [UIImage imageNamed:image_statusstop];
  3828. cell.reloadTaskButton.hidden = NO;
  3829. cell.stopTaskButton.hidden = YES;
  3830. } else {
  3831. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3832. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3833. cell.stopTaskButton.hidden = NO;
  3834. cell.reloadTaskButton.hidden = YES;
  3835. }
  3836. // se non c'è una preview in bianconero metti l'immagine di default
  3837. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3838. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_uploaddisable] color:[NCBrandColor sharedInstance].brand];
  3839. cell.labelTitle.enabled = NO;
  3840. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3841. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3842. if (progress > 0) {
  3843. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3844. else cell.progressView.progressTintColor = [UIColor blackColor];
  3845. cell.progressView.progress = progress;
  3846. cell.progressView.hidden = NO;
  3847. }
  3848. // ----------------------------------------------------------------------------------------------------------
  3849. // uploadFileError
  3850. // ----------------------------------------------------------------------------------------------------------
  3851. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3852. cell.labelTitle.enabled = NO;
  3853. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3854. if ([metadata.sessionError length] == 0)
  3855. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3856. else
  3857. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3858. }
  3859. }
  3860. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3861. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3862. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3863. return cell;
  3864. }
  3865. - (void)setTableViewFooter
  3866. {
  3867. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3868. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3869. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3870. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3871. UIFont *appFont = [UIFont systemFontOfSize:12];
  3872. footerLabel.font = appFont;
  3873. footerLabel.textColor = [UIColor grayColor];
  3874. footerLabel.backgroundColor = [UIColor clearColor];
  3875. footerLabel.textAlignment = NSTextAlignmentCenter;
  3876. NSString *folders;
  3877. NSString *files;
  3878. NSString *footerText;
  3879. if (_sectionDataSource.directories > 1) {
  3880. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3881. } else if (_sectionDataSource.directories == 1){
  3882. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3883. } else {
  3884. folders = @"";
  3885. }
  3886. if (_sectionDataSource.files > 1) {
  3887. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3888. } else if (_sectionDataSource.files == 1){
  3889. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3890. } else {
  3891. files = @"";
  3892. }
  3893. if ([folders isEqualToString:@""]) {
  3894. footerText = files;
  3895. } else if ([files isEqualToString:@""]) {
  3896. footerText = folders;
  3897. } else {
  3898. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3899. }
  3900. footerLabel.text = footerText;
  3901. [footerView addSubview:footerLabel];
  3902. [self.tableView setTableFooterView:footerView];
  3903. }
  3904. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3905. {
  3906. NSString *textMessage;
  3907. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3908. // se non può essere selezionata deseleziona
  3909. if ([cell isEditing] == NO)
  3910. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3911. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3912. if (self.tableView.editing) {
  3913. [self setTitle];
  3914. return;
  3915. }
  3916. // test crash
  3917. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3918. if (indexPath.row >= [metadatas count]) return;
  3919. // settiamo il record file.
  3920. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3921. //
  3922. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3923. // se è in corso una sessione
  3924. if ([_metadata.session length] > 0) return;
  3925. if (_metadata.errorPasscode) {
  3926. // se UUID è nil lo sta ancora caricando quindi esci
  3927. if (!_metadata.uuid) return;
  3928. // esiste un hint ??
  3929. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3930. // qui !! la richiesta della nuova passcode
  3931. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3932. // stesso UUID ... la password è stata modificata !!!!!!
  3933. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3934. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3935. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3936. [alertView show];
  3937. } else {
  3938. // UUID diverso.
  3939. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3940. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3941. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3942. [alertView show];
  3943. }
  3944. // chiediamo la passcode e ricarichiamo tutto.
  3945. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3946. viewController.delegate = self;
  3947. viewController.fromType = CCBKPasscodeFromPasscode;
  3948. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3949. viewController.passcodeInputView.maximumLength = 64;
  3950. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3951. viewController.inputViewTitlePassword = NO;
  3952. viewController.title = k_brand;
  3953. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3954. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3955. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3956. [self presentViewController:navigationController animated:YES completion:nil];
  3957. }
  3958. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3959. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3960. NSString* selector;
  3961. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3962. else selector = selectorLoadPlist;
  3963. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3964. return;
  3965. }
  3966. // se il plist è caricato ed è un modello aprilo
  3967. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3968. // file
  3969. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3970. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3971. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3972. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3973. } else {
  3974. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3975. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3976. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3977. }
  3978. }
  3979. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3980. }
  3981. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3982. {
  3983. [self setTitle];
  3984. }
  3985. #pragma --------------------------------------------------------------------------------------------
  3986. #pragma mark ===== Synchronize Folder Cell =====
  3987. #pragma --------------------------------------------------------------------------------------------
  3988. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3989. {
  3990. BOOL cryptated = NO;
  3991. CCCellMain *cell;
  3992. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3993. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3994. if (recordMetadata.directory == NO)
  3995. continue;
  3996. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3997. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3998. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  3999. cryptated = recordMetadata.cryptated;
  4000. break;
  4001. }
  4002. }
  4003. if (!cell)
  4004. return;
  4005. if (animation) {
  4006. NSURL *myURL;
  4007. if (cryptated)
  4008. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4009. else
  4010. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4011. } else {
  4012. cell.synchronizedImageView.image = nil;
  4013. }
  4014. }
  4015. #pragma --------------------------------------------------------------------------------------------
  4016. #pragma mark ===== Navigation ====
  4017. #pragma --------------------------------------------------------------------------------------------
  4018. - (BOOL)shouldPerformSegue
  4019. {
  4020. // if background return
  4021. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4022. if (self.view.window == NO)
  4023. return NO;
  4024. // Collapsed ma siamo già in detail esci
  4025. if (self.splitViewController.isCollapsed)
  4026. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4027. // Video in esecuzione esci
  4028. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4029. return YES;
  4030. }
  4031. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4032. {
  4033. id viewController = segue.destinationViewController;
  4034. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4035. CCMetadata *metadata;
  4036. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4037. UINavigationController *nav = viewController;
  4038. _detailViewController = (CCDetail *)nav.topViewController;
  4039. } else {
  4040. _detailViewController = segue.destinationViewController;
  4041. }
  4042. if ([sender isKindOfClass:[CCMetadata class]]) {
  4043. metadata = sender;
  4044. [allRecordsDataSourceImagesVideos addObject:sender];
  4045. } else {
  4046. metadata = _metadata;
  4047. for (NSString *fileID in _sectionDataSource.allFileID) {
  4048. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4049. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4050. [allRecordsDataSourceImagesVideos addObject:metadata];
  4051. }
  4052. }
  4053. _detailViewController.metadataDetail = metadata;
  4054. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4055. _detailViewController.dateFilterQuery = nil;
  4056. _detailViewController.isCameraUpload = NO;
  4057. [_detailViewController setTitle:metadata.fileNamePrint];
  4058. }
  4059. // can i go to next viewcontroller
  4060. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4061. {
  4062. NSString *nomeDir;
  4063. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4064. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4065. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4066. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4067. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4068. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4069. viewController.delegate = self;
  4070. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4071. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4072. viewController.inputViewTitlePassword = YES;
  4073. if ([CCUtility getSimplyBlockCode]) {
  4074. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4075. viewController.passcodeInputView.maximumLength = 6;
  4076. } else {
  4077. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4078. viewController.passcodeInputView.maximumLength = 64;
  4079. }
  4080. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4081. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4082. viewController.touchIDManager = touchIDManager;
  4083. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4084. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4085. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4086. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4087. [self presentViewController:navController animated:YES completion:nil];
  4088. return;
  4089. }
  4090. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4091. else nomeDir = _metadata.fileName;
  4092. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4093. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4094. if (viewController.isViewLoaded == false) {
  4095. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4096. viewController.isFolderEncrypted = _metadata.cryptated;
  4097. viewController.serverUrl = serverUrlPush;
  4098. viewController.titleMain = _metadata.fileNamePrint;
  4099. viewController.textBackButton = _titleMain;
  4100. // save self
  4101. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4102. }
  4103. // OFF SearchBar
  4104. [viewController cancelSearchBar];
  4105. [self.navigationController pushViewController:viewController animated:YES];
  4106. }
  4107. }
  4108. @end