CCMain.m 262 KB

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